티스토리 뷰
파이썬 2 3 차이 4가지 (python print, int, float, string unicode)
vicddory 2017. 2. 13. 07:30목차
파이썬 2 3 차이 4가지 (python print, int, float, string unicode)
1. print가 함수 형태로 변경
2.x style
1 2 | >>> print "welcome to", "python3k" welcome to python3k | cs |
3 style
1 2 | >>> print("welcome to","python3k") welcome to python3k | cs |
또한 인자로 다음과 같이 구분자(sep), 끝라인(end), 출력(file)을 지정할 수 있습니다.
1 2 | >>> print("welcome to","python3k", sep="~", end="!", file=sys.stderr) welcome to python3k | cs |
이와 유사하게 입출력 관련해서 변경된 점들이 많습니다.
raw_input이 input으로 변경되고, as, with 예약어가 추가되었습니다. 또한 새로운 문자열 포맷팅을 제공합니다.
2. long 형이 없어지고 int 형으로 통일
2.x style
1 2 | >>> type(2**31) <type 'long'> | cs |
3 style
1 2 3 4 5 | >>> type(2**31) <class 'int'> >>> type(2**40) <class 'int'> | cs |
위와 같이 2.x에서는 2의 31제곱이 long 형이었는데, 3에서는 2의 31제곱은 물론 2의 40제곱도 int형인 것을 확인할 수 있습니다.
즉, 2.x에서는 sys.maxint 이하의 값은 int로 처리되고 그 이상의 값은 long으로 처리되었는데 3에서부터는 모두 int로 처리됩니다.
2.x style
1 2 3 4 5 6 7 8 | >>> sys.maxint 2147483647 >>> type(sys.maxint) <type 'int'> >>> type(sys.maxint+1) <type 'long'> | cs |
파이썬 2 3 차이
3. "int/(나누기) int"의 결과는 float으로 처리
2.x style
1 2 | >>> 1/2 0 | cs |
1 2 | >>> 3/2 1 | cs |
3 style
1 2 3 4 5 | >>> 3/2 1.5 >>>type(2/2) <class 'float'> | cs |
사실 2.x에서는 int / int의 결과가 int로만 나와서 파이썬에 익숙지 않은 사용자에게 예상 밖의 결과가 나온 적이 많았지만 이제는 그럴 일이 적어질 것 같습니다.
파이썬 2 3 차이
4. String, Unicode 체계가 변경
파이썬 2.x에서는 아래 예제와 같이 string과 unicode로 구분이 되었습니다.
1 2 | >>> type('가') <- 일반 string의 경우 <type 'str'> | cs |
1 | >>>type('가'.decode('utf8')) <- 인코딩을 가지고 있는 문자열을 디코딩한 경우 | cs |
1 2 | >>> type(u'가') <type 'unicode'> <- 유니코드의 경우 | cs |
파이썬 2 3 차이
그러나 3에서는 아래 예제와 같이 string과 bytes로 구분됩니다.
1 2 | >>> type(u'가') SyntaxError: invalid syntax (<pyshell#13>, line 1) | cs |
1 2 | >>> type('가') <class 'str'> | cs |
1 2 | >>> type('가'.endoce('cp949')) <class 'bytes'> | cs |
즉, 파이썬 2.x에서는 일반 문자열이 인코딩이 있는 문자열이었고 유니코드가 따로 있었습니다.
하지만, 파이썬 3에서는 유니코드를 따로 지정하지 않고 일반 문자열이 기존의 유니코드와 동일하며, 인코딩이 있는 문자열은 bytes로 표현됩니다.
파이썬 2 3 차이 4가지 (python print, int, float, string unicode)