I wrote the following Python2.7 code to remove digits and the backslash character (\\) from some string. I attempted to use the str.translate method, because I had learned that it is very efficient. The code below successfully removed digits from the string x, but is unable to remove the single backslash in y. What did I do wrong?
import string
x = 'xb7'
y = '\xb7'
print x.translate(None, '\\' + string.digits)
print y.translate(None, '\\' + string.digits)
You don't have any strings with backslashes. x
has the characters 'x'
, 'b'
, and '7'
, while y
has a single character, '·'
, denoted by the hex code b7
. If you want the literal string '\\xb7'
, with four characters in it, use a raw string by prefixing an r
in front of the literal.
>>> import string
>>> print r'\xb7'.translate(None, '\\' + string.digits)
xb
Your algorithm works much better when there's actually a backslash to remove. Tigerhawk already showed you your hexadecimal string. Here's another simplistic example to help, showing the unchanged original y .
import string
x = 'xb7'
y = '\\xb7'
print x, y
kill = '\\' + string.digits
print "kill", kill
print x.translate(None, kill)
print y.translate(None, kill)
print "y=", y
Output:
xb7 \xb7
kill \0123456789
xb
xb
y= \xb7
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.