我想从python中的字符串中删除“\”

2024-05-19 02:54:16 发布

您现在位置:Python中文网/ 问答频道 /正文

Possible Duplicate:
How to refer to “\” sign in python string

我有相当大的字符串数据,其中我必须删除除A-Z、A-Z和0-9以外的所有字符 我几乎可以删除所有字符,但“\”是个问题。你知道吗

其他字符都会被删除,但“\”会产生问题

def replace_all(text, dic):
    for i, j in dic.iteritems():
        text = text.replace(i, j)
    return text

reps = {' ':'-','.':'-','"':'-',',':'-','/':'-',
        '<':'-',';':'-',':':'-','*':'-','+':'-',
        '=':'-','_':'-','?':'-','%':'-','!':'-',
        '$':'-','(':'-',')':'-','\#':'-','[':'-',
        ']':'-','\&':'-','@':'-','\W':'-','\t':'-'}

x.name = x.name.lower()

x1 = replace_all(x.name,reps)

Tags: totextnameinstringall字符replace
3条回答

birryee是正确的,你需要用第二个反斜杠来逃避反斜杠。你知道吗

I've quite large string data in which I've to remove all characters other than A-Z,a-z and 0-9

换句话说,您只希望保留这些字符。你知道吗

string类已经提供了一个测试“每个字符都是字母还是数字?”,称为.isalnum()。所以,我们可以filter

>>> filter(str.isalnum, 'foo-bar\\baz42')
'foobarbaz42'

如果有字符串:

a = 'hi how \\are you'

您可以通过执行以下操作将其删除:

a.replace('\\','')

>'hi how are you'

如果你有一个特定的背景,你有麻烦,我建议张贴一点更详细的。你知道吗

相关问题 更多 >

    热门问题