【发布时间】:2017-09-30 04:51:48
【问题描述】:
在 Python Unicode Howto 中,它说:
请注意,这些 [string] 方法的参数可以是 Unicode 字符串或 8 位字符串。 8 位字符串将在之前转换为 Unicode 进行操作; Python 的默认 ASCII 编码将是 使用过,所以大于 127 的字符会引发异常:
>>> s.find('Was\x9f') Traceback (most recent call last):
... UnicodeDecodeError: 'ascii' codec can't decode byte 0x9f in position 3: ordinal not in range(128)
>>> s.find(u'Was\x9f')
-1
https://docs.python.org/2/howto/unicode.html
所以你会假设一个 unicode 字符串可以在 find/replace/count 函数中使用 unicode 字符串,但看起来并不是那么简单。在 Python 控制台中查看:
>>> type(u'hi')
<type 'unicode'>
>>> type('i')
<type 'str'>
>>> type('mÑ')
<type 'str'>
>>> u'hi'.replace('i','m')
u'hm'
>>> u'hi'.replace('i','mÑ')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1: ordinal not in range(128)
>>> 'hi'.replace('i','mÑ')
'hm\xc3\x91'
那么,在任何类型的字符串中正确替换这种替换的最佳方法是 if else case 与所有 str 值,或者所有 u'values' 如果 str(type(input)) 具有 'unicode'?
更糟糕的是,无论有没有字符串前面的“u”,这似乎都没有做任何事情:
print((u"<head><script>%s</script>" % (thevariable,))
但只有当我使用from __future__ import unicode_literals ??
【问题讨论】:
-
最好的方法是使用一切都是 Unicode 的 python 3。只是说!
-
我建议在 Python 2 中避免使用像
'mÑ'这样的东西。如果你想在你的代码中使用 Unicode 文字字符串,那么总是使用像u'mÑ'这样的正确的 Unicode 字符串(当然你需要一个正确的编码指令脚本的顶部)。是的,Python 2 的方法可以处理纯字符串或 Unicode 字符串,但是如果将它们混合在一起会变得非常混乱。正如 Rahul 所说,Unicode 处理在 Python 3 中更加明智,其中字节字符串和文本字符串之间有明显的区别。 -
同时,您可能会发现这篇文章对您有所帮助:Pragmatic Unicode,由 SO 资深人士 Ned Batchelder 撰写。
-
谢谢,我认为 unicode 的 if/else 似乎适用于下载字符串和我拥有的文件中的替换字符串的奇怪情况。
标签: python string python-2.7 unicode encoding