【发布时间】:2018-01-05 12:58:45
【问题描述】:
我正在使用 Python 3.6 解析一个包含一些 UTF-8 编码文本的 XML 文件:
<line>
<text>Some text which could end with ¬</text>
</line>
我用xml.etree.ElementTree 解析它,我得到text 元素作为一个元素:
<Element 'text' at 0x105577c78>
我可以得到文本字符串
text_string = text.text.encode('utf-8')
msg = "Text string: {}".format(text_string)
self.stdout.write(self.style.SUCCESS(msg))
我得到:
Text string: b'Some text which could end with \xac'
现在我需要知道这个字符串是否以 ¬ 字符结尾:
if text_string.endswith('¬'):
print("The text ends which the char!")
但我明白了:
TypeError: endswith first arg must be bytes or a tuple of bytes, not str
如果我更改为if text_string.endswith(b'¬'):,我会收到另一个错误:
if text_string.endswith(b'\xac'):
^
SyntaxError: bytes can only contain ASCII literal characters.
我知道我很困惑,因为 text_string 是字节而不是字符串,但我不明白如何解决我的问题。
如何将字节转换为字符串? 或者如何在字节对象中搜索特殊字符?
谢谢!
【问题讨论】:
-
if text_string.endswith(b'\xac'):- eval.in/931046 -
您应该检查具有相同编码的字符串 ---
if text_string.endswith('¬'.encode('utf-8')): -
“所有字符都是特殊的。” -- tchrist
标签: python python-3.x encoding utf-8