Python中使用Unicode来处理国际化文本

有的时候碰到ASCII编码的字符串和非ASCII编码的字符的操作,会报如下错误。 

>>> char = "\xc3\xa4"
>>> print(char)
Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Python27\lib\codecs.py", line 357, in write
    data, consumed = self.encode(object, self.errors)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)
>>>

这个时候,使用Pytyon提供的内置的unicode类型。用法很简单:

>>> char_1 = '\xc3\xa4'
>>> char_2 = unicode(char_1, 'utf8')
>>> print(char_2)
ä
>>>

 

你可能感兴趣的:(【编程语言】)