Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.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在某些字符之前删除ByTestString中的所有内容_Python_String_Substring_Byte_Strip - Fatal编程技术网

Python在某些字符之前删除ByTestString中的所有内容

Python在某些字符之前删除ByTestString中的所有内容,python,string,substring,byte,strip,Python,String,Substring,Byte,Strip,我有下面的bytestring b'removethis\x00\x002020.10.14\x00\xf2\x00^\n\x84>\x01\x00\x10\x01\x14\x00\x00\x00\x00\x8d\xec\xdc0\x1bo\xe7\x15^\n\x84>\x01\x00\x10\x01\x04\x9b\ux18' 我希望删除第一个\x00之前的所有内容,以便基本上删除子字符串removethis 所以问题是,我只想删除第一个\x00之前的所有内容,而不是将来可能出现在字符串中的

我有下面的bytestring
b'removethis\x00\x002020.10.14\x00\xf2\x00^\n\x84>\x01\x00\x10\x01\x14\x00\x00\x00\x00\x8d\xec\xdc0\x1bo\xe7\x15^\n\x84>\x01\x00\x10\x01\x04\x9b\ux18'

我希望删除第一个
\x00
之前的所有内容,以便基本上删除子字符串
removethis


所以问题是,我只想删除第一个
\x00
之前的所有内容,而不是将来可能出现在字符串中的任何
\x00
,我不确定如何执行此操作。

您可以为此构建一个正则表达式

import re

txt = "b'removethis\x00\x002020.10.14\x00\xf2\x00^\n\x84>\x01\x00\x10\x01\x14\x00\x00\x00\x8d\xec\xdc0\x1bo\xe7\x15^\n\x84>\x01\x00\x10\x01\x04\x9b_\x18'"
x = re.search("\\x00.*", txt)
print(x)

在这里,我们找到第一个出现的
\x00
,然后使用
*
将所有内容都带到字符串末尾。结果是您的字符串减去'removethis'

在第一个之后…
是一个打字错误,我想。我怎样才能再次将其转换为bytestring?。这要求bytestring“txt”加引号,这只会将其转换为字符串。@Emil B您可以使用
txt\u in\u bytes\u再次=bytes(txt,'utf-8'将其转换为bytes)
它返回如下格式@EmilB您可以通过调用
x.group(0)
从正则表达式结果中获得匹配的文本,这是整个匹配的文本