Python如何从字符串中去除转义字符

3
我有一个字符串如下,我想在Python中将字符串中的所有\x06字符都删除。
例如:
s = 'test\x06\x06\x06\x06'
s1 = 'test2\x04\x04\x04\x04'
print(literal_eval("'%s'" % s))

输出: test♠♠♠♠

我只需要字符串test并删除所有的\xXX。


\x04是什么意思? - Mad Physicist
2
还有,是字符串还是字节?Py 2 还是 Py 3?你尝试过什么?你做了哪些研究? - Mad Physicist
2
可能是重复的问题:如何从字符串列表中删除所有转义序列? - Sociopath
1
@davedwards 我已经尝试过这个,它返回了test♠♠♠♠。我只需要字符串“test”。 - ashkus
2
@ashkus 你说得对,这个怎么样:import re; re.sub('[^A-Za-z0-9]+', '', s) - chickity china chinese chicken
显示剩余4条评论
3个回答

6
也许正则表达式模块是解决问题的方法。
>>> s = 'test\x06\x06\x06\x06'
>>> s1 = 'test2\x04\x04\x04\x04'
>>> import re
>>> re.sub('[^A-Za-z0-9]+', '', s)
'test'
>>> re.sub('[^A-Za-z0-9]+', '', s1)
'test2'

2
如果您想删除所有的\xXX字符(不可打印ASCII字符),最好的方法可能是这样的:
import string

def remove_non_printable(s):
    return ''.join(c for c in s if c not in string.printable)

请注意,此方法无法处理任何非 ASCII 可打印字符(例如 é,将会被删除)。

0

这应该可以做到

import re #Import regular expressions
s = 'test\x06\x06\x06\x06' #Input s
s1 = 'test2\x04\x04\x04\x04' #Input s1
print(re.sub('\x06','',s)) #remove all \x06 from s
print(re.sub('\x04','',s1)) #remove all \x04 from s1

1
正则表达式对于这个方法来说有些过头了,只需要使用 str.replace 即可。 - FHTMitchell
我相信在第二个打印语句中应该是's1',而不是's'。 - Sergey Makhonin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接