我想拆分字符串 我有 £300
但似乎拆分函数首先将其转换为 ascii 和之后。但我无法像以前一样将它转换回 unicode。
有没有其他方法可以像下面的代码片段那样拆分这样一个 unicode 字符串而不破坏它。
# -*- coding: utf-8 -*-
mystring = 'I have £300.'
alist = mystring.split()
alist = [item.decode("utf-8") for item in alist]
print "alist",alist
print "mystring.split()",mystring.split()
#I want to get [I,have,£300]
#I get: ['I', 'have', '\xc2\xa3300.']
最佳答案
您正在查看 python 2 显示 数据的方式的局限性。
使用 python 2:
>>> mystring = 'I have £300.'
>>> mystring.split()
['I', 'have', '\xc2\xa3300.']
但是,请注意它会按照您的意愿打印:
>>> print(mystring.split()[2])
£300.
相比之下,使用 python 3,它会按照您的意愿显示:
>>> mystring = 'I have £300.'
>>> mystring.split()
['I', 'have', '£300.']
使用 python 3 的一个主要原因是它对 unicode 的出色处理。
关于python - 无法在不转换为 ascii 的情况下拆分 unicode 字符串 - python 2.7,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39216381/