简体   繁体   中英

Python how to remove escape characters from a string

I have a string like below, and I want to remove all \\x06 characters from the string in Python.

Ex:

s = 'test\x06\x06\x06\x06'
s1 = 'test2\x04\x04\x04\x04'
print(literal_eval("'%s'" % s))

output: test♠♠♠♠

I just need String test and remove all \\xXX.

Maybe the regex module is the way to go

>>> 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'

If you want to remove all \\xXX characters (non-printable ascii characters) the best way is probably like so

import string

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

Note this won't work with any non-ascii printable characters (like é , which will be removed).

This should do it

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM