在Python中,我有一个Unicode编码的文本.此文本包含不间断的空格,我想将其转换为"x".不间断的空间等于chr(160).我有以下代码,当我使用Localhost通过Eclipse运行它作为Django时效果很好.没有错误和任何不间断的空格被转换.
my_text = u"hello"
my_new_text = my_text.replace(chr(160), "x")
Run Code Online (Sandbox Code Playgroud)
但是当我以任何其他方式运行它时(Python命令行,Django通过runserver而不是Eclipse)我收到一个错误:
'ascii' codec can't decode byte 0xa0 in position 0: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)
我想这个错误是有道理的,因为它试图将Unicode(my_text)与非Unicode的东西进行比较.我的问题是:
chr(160)不是Unicode,它是什么?my_text绝对是Unicode.Fre*_*Foo 11
chr(160)是一个长度为1的字节字符串,其唯一字节的值为160或十六进制a0.除了特定编码的上下文之外,没有任何意义.NO-BREAK SPACE,即代码点160,那就是unichr(160).例如,
>>> u"hello\u00a0world".replace(unichr(160), "X")
u'helloXworld
Run Code Online (Sandbox Code Playgroud)