简体   繁体   English

用str.translate删除反斜杠

[英]Remove backslash with str.translate

I wrote the following Python2.7 code to remove digits and the backslash character (\\) from some string. 我编写了以下Python2.7代码,以从某些字符串中删除数字和反斜杠字符(\\)。 I attempted to use the str.translate method, because I had learned that it is very efficient. 我尝试使用str.translate方法,因为我了解到它非常有效。 The code below successfully removed digits from the string x, but is unable to remove the single backslash in y. 下面的代码成功删除了字符串x中的数字,但无法删除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 . x具有字符'x''b''7' ,而y具有单个字符'·' ,由十六进制代码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. 如果要使用文字字符串'\\xb7' (其中包含四个字符),请通过在文字前面加上r来使用原始字符串。

>>> 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. Tigerhawk已经向您显示了您的十六进制字符串。 Here's another simplistic example to help, showing the unchanged original y . 这是另一个简单的示例,可以显示未更改的原始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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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