gpt4 book ai didi

python - 使用 Python 检查字节字符串是否以特殊字符结尾

转载 作者:太空宇宙 更新时间:2023-11-03 14:18:18 34 4
gpt4 key购买 nike

我正在使用 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'):
if text_string.endswith('¬'.encode('utf-8')):

关于python - 使用 Python 检查字节字符串是否以特殊字符结尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48114158/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com