2013-05-10 2 views
2

어, 파이썬 2/3는 너무 실망 ... 예, test.py 생각해 그것을 실행파이썬 2와 3 모두에서 유니 코드 문자열 길이가 같습니까?

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 

import sys 
if sys.version_info[0] < 3: 
    text_type = unicode 
    binary_type = str 
    def b(x): 
    return x 
    def u(x): 
    return unicode(x, "utf-8") 
else: 
    text_type = str 
    binary_type = bytes 
    import codecs 
    def b(x): 
    return codecs.latin_1_encode(x)[0] 
    def u(x): 
    return x 

tstr = " ▲ " 

sys.stderr.write(tstr) 
sys.stderr.write("\n") 
sys.stderr.write(str(len(tstr))) 
sys.stderr.write("\n") 

:

$ python2.7 test.py 
▲ 
5 
$ python3.2 test.py 
▲ 
3 

우수함, 나는 두 개의 서로 다른 문자열 크기를 얻을. 다행스럽게도 그물 주변에서 발견 된 이러한 래퍼 중 하나에 문자열을 래핑하는 것이 도움이 될까요? tstr = text_type(" ▲ ") 들어

:

$ python2.7 test.py 
Traceback (most recent call last): 
    File "test.py", line 21, in <module> 
    tstr = text_type(" ▲ ") 
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 1: ordinal not in range(128) 
$ python3.2 test.py 
▲ 
3 

tstr = u(" ▲ ")를 들어

$ python2.7 test.py 
Traceback (most recent call last): 
    File "test.py", line 21, in <module> 
    tstr = u(" ▲ ") 
    File "test.py", line 11, in u 
    return unicode(x) 
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 1: ordinal not in range(128) 
$ python3.2 test.py 
▲ 
3 

tstr = b(" ▲ ")를 들어

$ python2.7 test.py 
▲ 
5 
$ python3.2 test.py 
Traceback (most recent call last): 
    File "test.py", line 21, in <module> 
    tstr = b(" ▲ ") 
    File "test.py", line 17, in b 
    return codecs.latin_1_encode(x)[0] 
UnicodeEncodeError: 'latin-1' codec can't encode character '\u25b2' in position 1: ordinal not in range(256) 

tstr = binary_type(" ▲ ")를 들어

$ python2.7 test.py 
▲ 
5 
$ python3.2 test.py 
Traceback (most recent call last): 
    File "test.py", line 21, in <module> 
    tstr = binary_type(" ▲ ") 
TypeError: string argument without an encoding 

글쎄, 확실히 쉬운 일입니다.

그래서 파이썬 2.7과 3.2에서 같은 문자열 길이 (이 경우 3)를 얻는 방법은 무엇입니까?

답변

3

글쎄, 2.7이 encoding 인수를 가지고 파이썬에서 unicode()을 밝혀, 그 분명히하는 데 도움이 :

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 

import sys 
if sys.version_info[0] < 3: 
    text_type = unicode 
    binary_type = str 
    def b(x): 
    return x 
    def u(x): 
    return unicode(x, "utf-8") 
else: 
    text_type = str 
    binary_type = bytes 
    import codecs 
    def b(x): 
    return codecs.latin_1_encode(x)[0] 
    def u(x): 
    return x 

tstr = u(" ▲ ") 

sys.stderr.write(tstr) 
sys.stderr.write("\n") 
sys.stderr.write(str(len(tstr))) 
sys.stderr.write("\n") 

이 실행, 내가 필요한 것을 얻을 :

$ python2.7 test.py 
▲ 
3 
$ python3.2 test.py 
▲ 
3 
관련 문제