내장 함수 개요
파이썬 인터프리터에 기본 제공되는 69개의 함수로, 별도 모듈 임포트 없이 사용 가능
공식 문서 참고: https://docs.python.org/3/library/functions.html#staticmethod
타입 변환 함수 (8개)
(1) 정수 변환 - int()
# 숫자 형태 문자열을 정수로 변환
data = '777'
print(int(data)) # 777
(2) 실수 변환 - float()
# 문자열 또는 정수를 실수로 변환
text = '12'
number = 12
print(float(text)) # 12.0
print(float(number)) # 12.0
(3) 문자열 변환 - str()
# 정수를 문자열로 변환
value = 15
print(str(value) + '3') # 153
(4) 불리언 변환 - bool()
empty_list = []
zero_val = 0
null_val = None
positive = 2
print(bool(empty_list), type(bool(empty_list))) # False <class 'bool'>
print(bool(zero_val), type(bool(zero_val))) # False <class 'bool'>
print(bool(null_val), type(bool(null_val))) # False <class 'bool'>
print(bool(positive), type(bool(positive))) # True <class 'bool'>
(5) 리스트 변환 - list()
# 이터러블 객체를 리스트로 변환
print(list('python')) # ['p', 'y', 't', 'h', 'o', 'n']
(6) 튜플 변환 - tuple()
# 이터러블 객체를 튜플로 변환
print(tuple('데이터')) # ('데', '이', '터')
(7) 딕셔너리 변환 - dict()
# 키-값 쌍의 이터러블을 딕셔너리로 변환
mapping = dict([(1, 'first'), (2, 'second'), (3, 'third')])
print(mapping) # {1: 'first', 2: 'second', 3: 'third'}
(8) 집합 변환 - set()
# 중복 제거를 위한 집합 생성
duplicates = [2, 2, 3, 3, 4, 4]
print(set(duplicates)) # {2, 3, 4}
진수 변환 함수 (3개)
(1) 10진수 → 2진수 - bin()
decimal_num = 888
print(bin(decimal_num)) # 0b1101111000
(2) 10진수 → 8진수 - oct()
decimal_num = 888
print(oct(decimal_num)) # 0o1570
(3) 10진수 → 16진수 - hex()
decimal_num = 888
print(hex(decimal_num)) # 0x378
수학 연산 함수 (8개)
(1) 절대값 계산 - abs()
negative_a = -234
negative_b = -5
print(abs(negative_a)) # 234
print(abs(negative_b)) # 5
(2) 몫과 나머지 - divmod()
result = divmod(14, 4)
print(result) # (3, 2) - (몫, 나머지)
(3) 반올림 - round()
print(round(3.601)) # 4
print(round(3.5)) # 4
print(round(4.151, 1)) # 4.2
print(round(4.15, 1)) # 4.1
(4) 거듭제곱 - pow()
print(3 ** 5) # 243
print(pow(3, 5)) # 243
print(pow(3, 5, 4)) # 3
print(pow(3, 5.0)) # 243.0
(5) 합계 계산 - sum()
print(sum([2, 3, 4])) # 9
(6) 최솟값 - min()
print(min(2, 3, 4, 5, 6, 7, 8, 9, 10, 11)) # 2
(7) 최댓값 - max()
print(max(2, 3, 4, 5, 6, 7, 8, 9, 10, 11)) # 11
(8) 복소수 생성 - complex()
num1 = complex(3, 4)
num2 = complex(5, 6)
print(num1) # (3+4j)
print(num2) # (5+6j)
print(num1 + num2) # (8+10j)
데이터 구조 관련 함수 (18개)
시퀀스 관련 (5개)
역순 정렬 - reversed()
word = 'sample'
reversed_word = reversed(word)
print(reversed_word, type(reversed_word)) # <reversed object> <class 'reversed'>
print(list(reversed_word)) # ['e', 'l', 'p', 'm', 'a', 's']
슬라이싱 - slice()
sequence = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(sequence[0:4]) # [1, 2, 3, 4]
print(sequence[slice(0, 4)]) # [1, 2, 3, 4]
길이 계산 - len()
print(len('sample')) # 6
정렬 - sorted()
numbers = [12, 10, 3, 6, 4, 5]
print(sorted(numbers)) # [3, 4, 5, 6, 10, 12]
print(sorted(numbers, reverse=True)) # [12, 10, 6, 5, 4, 3]
print(sorted(numbers, reverse=False)) # [3, 4, 5, 6, 10, 12]
words = ['sample', 'test', 'demo', 's']
def get_length(item):
return len(item)
print(sorted(words, key=get_length)) # ['s', 'demo', 'test', 'sample']
인덱스 열거 - enumerate()
items = ['sample', 'test', 'demo', 's']
for idx, element in enumerate(items):
print(idx, element)
# 0 sample
# 1 test
# 2 demo
# 3 s
for idx, element in enumerate(items, 1):
print(idx, element)
# 1 sample
# 2 test
# 3 demo
# 4 s
문자열 처리 (4개)
형식 지정 - format()
text = 'sampledata'
print(format(text, "^20")) # 중앙 정렬
print(format(text, "<20")) # 좌측 정렬
print(format(text, ">20")) # 우측 정렬
print(format(100, 'b')) # 1100100
print(format(0b1100100, 'd')) # 100
print(format(100, 'o')) # 144
print(format(100, 'x')) # 64
print(format(100, 'X')) # 64
print(format(100, 'c')) # d
print(format(234567890, 'e')) # 2.345679e+08
print(format(234567890, '0.2e')) # 2.35e+08
print(format(234567890, '0.2E')) # 2.35E+08
print(format(2.34567890, 'f')) # 2.345679
print(format(2.34567890, '0.2f')) # 2.35
print(format(2.34567890, '0.10f')) # 2.3456789000
print(format(2.34567890e+4, 'F')) # 23456.789000
바이트 변환 - bytes()
korean_text = '한글데이터'
print(korean_text.encode()) # b'\xed\x95\x9c\xea\xb8\x80\xeb\x8d\xb0\xec\x9d\xb4\xed\x84\xb0'
print(bytes(korean_text, encoding='utf-8')) # b'\xed\x95\x9c\xea\xb8\x80\xeb\x8d\xb0\xec\x9d\xb4\xed\x84\xb0'
바이트 배열 - bytearray()
byte_data = bytearray('데이터', encoding='utf-8')
print(byte_data) # bytearray(b'\xeb\x8d\xb0\xec\x9d\xb4\xed\x84\xb0')
byte_data[0] = 70 # ASCII 'F'
byte_data[1] = 71 # ASCII 'G'
byte_data[2] = 72 # ASCII 'H'
print(byte_data.decode('utf-8')) # FGH이터
원시 문자열 - repr()
formatted = '데이터\n%d개\t항목' % 15
print(formatted)
# 데이터
# 15개 항목
print(repr(formatted))
# '데이터\\n15개\\t항목'
문자 인코딩 (3개)
문자 → 코드 - ord()
print(ord('2')) # 50
print(ord('가')) # 44032
코드 → 문자 - chr()
print(chr(100)) # d
print(chr(20000)) # 䀀
ASCII 표현 - ascii()
print(ascii('bbb')) # 'bbb'
print(ascii('2')) # '2'
불변 집합 - frozenset()
normal_set = {2, 3, 4}
normal_set.add(5)
print(normal_set) # {2, 3, 4, 5}
immutable_set = frozenset(normal_set)
print(immutable_set, type(immutable_set)) # frozenset({2, 3, 4, 5}) <class 'frozenset'>
# immutable_set.add(10) # 오류 발생
조건 판단 (2개)
모두 참 - all()
print(all([2, 0, 4, None])) # False
하나라도 참 - any()
print(any([2, 0, 4, None])) # True
고차 함수 (3개)
묶기 - zip()
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9]
names = ['kim', 'lee', 'park']
teams = ['A팀', 'B팀', 'C팀', 'D팀']
print(zip(nums, names, teams)) # <zip object>
print(list(zip(nums, names, teams))) # [(1, 'kim', 'A팀'), (2, 'lee', 'B팀'), (3, 'park', 'C팀')]
필터링 - filter()
def is_even(n):
return n % 2 == 0
data_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
filtered_result = filter(is_even, data_list)
print(filtered_result) # <filter object>
print(list(filtered_result)) # [2, 4, 6, 8, 10]
data_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(filter(lambda x: x % 2 == 0, data_list)) # <filter object>
print(list(filter(lambda x: x % 2 == 0, data_list))) # [2, 4, 6, 8, 10]
매핑 - map()
values = [1, 2, 3, 4, 5, 6, 7, 8, 9]
def square(x):
return x ** 2
mapped_result = map(square, values)
print(mapped_result) # <map object>
print(list(mapped_result)) # [1, 4, 9, 16, 25, 36, 49, 64, 81]
스코프 함수 (2개)
global_var = 2
def scope_test():
local_var = 3
print(locals()) # {'local_var': 3}
print(globals())
scope_test()
이터레이터/제너레이터 함수 (3개)
범위 생성 - range()
print(range(0, 4)) # range(0, 4)
이터레이터 생성 - iter()
text = 'sample'
iterator = iter(text)
print(iterator, type(iterator)) # <str_iterator object> <class 'str_iterator'>
다음 값 추출 - next()
text = 'sample'
iterator = iter(text)
print(iterator, type(iterator)) # <str_iterator object> <class 'str_iterator'>
print(next(iterator)) # s
문자열 코드 실행 함수 (3개)
평가 및 반환 - eval()
expression = input('덧셈식 입력 (예: x+y):')
print(eval(expression))
실행만 - exec()
exec(input('숫자 입력:'))
print(exec(input('소문자 입력:')))
컴파일 - compile()
expr1 = '2+3+4'
compiled_exec = compile(expr1, '', 'exec')
print(exec(compiled_exec)) # None
expr2 = '5+6+7'
compiled_eval = compile(expr2, '', 'eval')
print(eval(compiled_eval)) # 18
해시 함수
immutable_data = '456'
mutable_data = [2, 3, 4]
print(hash(immutable_data)) # 해시값 출력
# print(hash(mutable_data)) # TypeError 발생
도움말 함수
print(help(print))
호출 가능성 검사
value = 2
def square_func(x):
return x ** 2
print(callable(value)) # False
print(callable(square_func)) # True
속성 확인
dir() 함수는 객체의 __dir__() 메서드를 호출하여 내장 속성을 표시합니다
메모리 관련 (2개)
메모리 뷰 - memoryview()
mem_view = memoryview(bytearray('데이터', 'utf-8'))
print(list(mem_view)) # [235, 141, 176, 236, 157, 132, 235, 139, 164]