don*_*ame 26 python string unicode text
我在Python中遇到一个非常基本的字符串问题(我无法弄清楚).基本上,我正在尝试执行以下操作:
'# read file into a string
myString = file.read()
'# Attempt to remove non breaking spaces
myString = myString.replace("\u00A0"," ")
'# however, when I print my string to output to console, I get:
Foo **<C2><A0>** Bar
Run Code Online (Sandbox Code Playgroud)
我认为"\ u00A0"是unicode非破坏空间的转义码,但显然我没有正确地做到这一点.关于我做错了什么的任何想法?
Kat*_*one 41
您没有unicode字符串,而是UTF-8字节列表(Python 2.x中的字符串).
尝试
myString = myString.replace("\xc2\xa0", " ")
Run Code Online (Sandbox Code Playgroud)
更好的方法是切换到unicode - 请参阅此文章以获取创意.你可以说
uniString = unicode(myString, "UTF-8")
uniString = uniString.replace(u"\u00A0", " ")
Run Code Online (Sandbox Code Playgroud)
并且它也应该工作(警告:我现在没有Python 2.x可用),虽然在将文件发送到文件或将其打印到屏幕时需要将其转换回字节(二进制).
我加入另一个答案,一个老问题之前犹豫,但由于Python3计数一个Unicode“非休息空间”字符为空白字符,并且因为串都是Unicode默认情况下,你可以摆脱不断裂空间的字符串中的s
使用join
并且split
,像这样:
s = ' '.join(s.split())
Run Code Online (Sandbox Code Playgroud)
当然,这也会更改任何其他空白区域(制表符、换行符等)。请注意,这仅适用于 Python3。
在你写的内容中没有任何迹象表明你一定做错了什么:如果原始字符串在“Foo”和“Bar”之间有一个不间断的空格,那么现在那里有一个正常的空格。这假设在某个时刻您已经将输入字符串(我认为是字节字符串,除非您使用的是 Python 3 或者file
使用模块中的函数打开codecs
)解码为 Unicode 字符串,否则您不太可能找到非 unicode 字节字符串中的 unicode 字符,用于replace
. 但是,仍然没有明显迹象表明您所写的内容存在问题。
您能否澄清输入是什么(repr(myString)
在替换之前打印)和输出是什么(在替换之后repr(myString)
再次打印)以及为什么您认为这是一个问题?如果没有,实际上不同的字符串可能看起来相同,但有帮助。repr
repr