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

标签 python python-3.x encoding utf-8

我正在使用 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/

相关文章:

python - 在 Python lmfit 中使用多个自变量

python-3.x - 在python中使用正则表达式获取一组数字

authentication - 了解跨域用户认证

python - 如何使用 python 以更快的方式执行 100000 次 2d fft?

python - 使用 Python/BeautifulSoup 迭代 .txt 文件中的多个 URL

python - Python 中的树似乎构建不正确

C# - 比较不同编码的字符串

html - 除了转义之外,HTML 实体是否还需要其他内容?

python - 使用牛顿法求解 Python 中的非线性方程组

mysql - python3计算自上次mysql数据输入以来的分钟数