Data Type
int
# 0xFF (16진수), 0o56 (8진수)
int(3.5) # 3
float
2e3 # 2000.0
float("1.6") # 1.6
float("inf") # 무한대
float("-inf") # -무한대
Complex
- 복소수
v = 2 + 3j v.real # 2 v.imag # 3
bool
- True/False는 Built-in Constants
bool(0) # False. 숫자에서 0만 False임, bool(-1) # True bool("False") # True
None
- None은 Built-in Constants
- Null과 같은 표현
a = None # a는 None a is None # a가 None 이므로 True
str
- Immutable 타입
- 기본적으로 유니코드
- 문자열을 표현하는 클래스 (한 문자도 char가 아닌 문자열 str 타입)
s = "ABC" type(s[1]) # class 'str'
- String Example
"Hello World" 'Python is fun' """Life is too short, You need python""" '''Life is too short, You need python''' food = "Python's favorite food is perl" food = 'Python\'s favorite food is perl' say = '"Python is very easy." he says.' say = "\"Python is very easy.\" he says." s = '아리랑\n아리랑\n아라리요'
r'문자열' : Escape Sequence를 표현하지 않고 Raw String을 직접 사용한다는 것을 의미
path = r'C:\Temp\test.csv' # 윈도우즈 파일경로
Operation
print("=" * 50) print("My Program") print("=" * 50) ================================================== My Program ==================================================
Indexing
>>> a = "Life is too short, You need Python" >>> a[3] 'e' >>> a[-1] 'n'
Slicing
>>> a = "Life is too short, You need Python" >>> a[0:4] 'Life' >>> a[:17] 'Life is too short' >>> a[19:] 'You need Python' >>> a[19:-7] 'You need'
Functions
Formatting
>>> number = 10 >>> day = "three" >>> "I ate {0} apples. so I was sick for {1} days.".format(number, day) >>> "I ate {0} apples. so I was sick for {day} days.".format(10, day=3)
Find & Index find : 만약 찾는 문자나 문자열이 존재하지 않는다면 -1 index: 문자열 안에 존재하지 않는 문자를 찾으면 오류가 발생
>>> a = "Python is best choice" >>> a.find('b') # 10 >>> a.find('k') # -1 >>> a.index('k') # ValueError: substring not found
Partition 문자열을 partition() 메서드의 첫번째 파라미터로 분리하여 prefix, separator, suffix 등 3개의 값을 Tuple로 리턴
>>> departure, _, arrival = "Seattle-Seoul".partition('-') >>> print(departure) Seattle
Join 문자열 삽입
>>> a= "," >>> a.join('abcd') # 'a,b,c,d' >>> ','.join(['가나','다라','마바']) # 가나,다라,마바 >>> ''.join(['가나','다라','마바']) # 가나다라마바
Etc
count(A) upper(),lower() strip(),lstrip(), rstrip() replace(A, B), split(A)
Bytes
- 바이트들을 표현하는 클래스
- bytes는 한번 설정되면 다시 변경할 수 없는 Immutable 타입
문자열을 바이트로 표현하기 위해 b'문자열' 와 같이 접두어 b를 앞에 붙임
text = b'abcde' for char in text: print (char) 97 98 99 100 101
encode() : 문자열을 바이트들로 변경하는 인코딩
- decode() : 바이트들을 문자열로 변경하는 디코딩
s1 = 'A\u00e5' # 'Aå' b = s1.encode('utf-8') # b'A\xc3\xa5' s2 = b.decode('utf-8') # 'Aå'