我有一个如下所示的字符串,我想从 Python 中的字符串中删除所有 \x06 个字符。
前任:
s = 'testx06x06x06x06'
s1 = 'test2x04x04x04x04'
print(literal_eval("'%s'" % s))
输出: 测试♠♠♠♠
我只需要字符串测试并删除所有 \xXX。
也许正则表达式模块是要走的路
>>> s = 'testx06x06x06x06'
>>> s1 = 'test2x04x04x04x04'
>>> import re
>>> re.sub('[^A-Za-z0-9]+', '', s)
'test'
>>> re.sub('[^A-Za-z0-9]+', '', s1)
'test2'
如果要删除所有xXX
字符(不可打印的ascii字符(,最好的方法可能是这样的
import string
def remove_non_printable(s):
return ''.join(c for c in s if c not in string.printable)
请注意,这不适用于任何非 ASCII 可打印字符(如 é
,这些字符将被删除(。
这应该可以做到
import re #Import regular expressions
s = 'testx06x06x06x06' #Input s
s1 = 'test2x04x04x04x04' #Input s1
print(re.sub('x06','',s)) #remove all x06 from s
print(re.sub('x04','',s1)) #remove all x04 from s1