3

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.

FHTMitchell
  • 11,793
  • 2
  • 35
  • 47
ashkus
  • 175
  • 1
  • 3
  • 15

3 Answers3

6

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

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).

FHTMitchell
  • 11,793
  • 2
  • 35
  • 47
0

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
Neal Titus Thomas
  • 483
  • 1
  • 6
  • 16