Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Python检查字节字符串是否以特殊字符结尾_Python_Python 3.x_Encoding_Utf 8 - Fatal编程技术网

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

使用Python检查字节字符串是否以特殊字符结尾,python,python-3.x,encoding,utf-8,Python,Python 3.x,Encoding,Utf 8,我正在解析一个XML文件,其中包含一些使用Python 3.6进行UTF-8编码的文本: <line> <text>Some text which could end with ¬</text> </line> 我可以用 text_string = text.text.encode('utf-8') msg = "Text string: {}".format(text_string) self.stdout.write(self.style

我正在解析一个XML文件,其中包含一些使用Python 3.6进行UTF-8编码的文本:

<line>
  <text>Some text which could end with ¬</text>
</line>
我可以用

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\u string
是字节而不是字符串,但我不明白如何解决我的问题

如何将字节转换为字符串? 或者如何在字节对象中搜索特殊字符


谢谢

谢谢

两人都在工作中提出建议:

if text_string.endswith(b'\xac'):
if text_string.endswith('¬'.encode('utf-8')):
对于Python2.7,如果没有给出其他编码提示,则默认为ASCII编码。看这个

因此,如果您使用的是Python2.7,请将以下注释放在程序脚本的顶部,然后一切都应该正常工作

#-*-编码:utf-8-*-
对于Python 3.x,默认为UTF-8编码,因此需要更改以下内容:

发件人:

text\u string=text.text.encode('utf-8')
致:

text\u string=text.text

希望这有帮助。

如果text\u string.endswith(b'\xac'):
您应该检查编码相同的字符串---
如果text\u string.endswith('',.encode('utf-8')):
“所有字符都是特殊的。”--他们没有将Python 3中的默认值更改为utf-8吗?快速搜索文档后,请标记Ransom,我认为您是正确的。Python3.x似乎默认为UTF-8。我将相应地编辑上面的评论。我想知道为什么原来的帖子在3.x版本中不起作用。我认为错误信息是不言自明的:字节只能包含ASCII文字字符。我不知道为什么非ASCII码是不被允许的,这对我来说似乎是一个相当武断的决定。由于编码已经是UTF-8,因此encode函数将变量从更改为。再次编辑我的帖子以合并解决方案。感谢你的抽检标记赎金,结果是一个更好的答案正在产生。
if text_string.endswith(b'\xac'):
if text_string.endswith('¬'.encode('utf-8')):