在特定字符后剪辑Python字符串

2024-04-25 05:53:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个程序,在这个程序中我将字节转换成utf-16字符串。但是,有时候字符串会继续,因为后面有0,而我的字符串会像这样结束:“这是我的字符串x00\x00\x00"。当我到达第一个\x00x00时,我想修剪字符串,这表示后面的0。在python中如何做到这一点?在

我的问题不是另一个在评论中链接的问题的重复,因为trim()不能完全工作。如果我有一个字符串是“This is my string x00\x00hi therex00\x00"我只想“This is my string”而trim会返回“This is my string hi there”


Tags: 字符串程序string字节is链接my评论
2条回答

使用index('\x00')获取第一个空字符的索引,并将字符串切片到索引

mystring = "This is my string\x00\x00\x00hi there\x00"
terminator = mystring.index('\x00')

print(mystring[:terminator])
# "This is my string"

您也可以split()在空字符上

^{pr2}$

使用strip()函数可以消除一些您不需要的字符,例如:

a = 'This is my string \x00\x00\x00'
b = a.strip('\x00') # or you can use rstrip() to eliminate characters at the end of the string
print(b)

您将得到This is my string作为输出。在

相关问题 更多 >