【问题标题】:Replacing sometimes causes exceptions in unicode strings替换有时会导致 unicode 字符串出现异常
【发布时间】: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


【解决方案1】:

u'hi'.replace('i','mÑ') 的情况下,您有一个 Unicode 字符串,因此替换需要 Unicode 字符串。两者都是字节字符串,因此它们使用默认的ascii 编解码器进行转换,而Ñ 不是ASCII。

'hi'.replace('i','mÑ') 的情况下,您有一个字节字符串,因此替换需要字节字符串。这就是你给它的,所以它有效。在 Python 2.7 中,具有非 ASCII 的字节字符串在源编码中进行编码,因此我希望您在脚本顶部有一个 #coding:utf8 并将源代码保存在 UTF-8 中,因为 \xc3\x91 是 UTF-8 Ñ.

Python 3 禁止在字节字符串常量中使用非 ASCII 字符(您仍然可以嵌入十六进制转义符,例如 b'm\xc3\x91',但 b'mÑ' 会出错)并且在使用错误类型时不会进行隐式编码/解码,因此它有助于清晰地分离问题。

【讨论】:

    猜你喜欢
    • 2021-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-13
    相关资源
    最近更新 更多