Python比较字符串忽略特殊字符

Roh*_*ith 7 python python-2.7

我想比较两个字符串,以便比较应忽略特殊字符的差异.那是,

海,这是一个考验

应该配合

海!这是一个测试"或"海这是一个测试

有没有办法在不修改原始字符串的情况下执行此操作?

roo*_*oot 16

这会在进行比较之前删除标点符号和空格:

In [32]: import string

In [33]: def compare(s1, s2):
    ...:     remove = string.punctuation + string.whitespace
    ...:     return s1.translate(None, remove) == s2.translate(None, remove)

In [34]: compare('Hai, this is a test', 'Hai ! this is a test')
Out[34]: True
Run Code Online (Sandbox Code Playgroud)

  • 它与 Python3 不兼容。 (5认同)
  • @AdamDobrawy:使用 `str.maketrans(dict.fromkeys(remove))` 作为映射(第一个参数)。 (2认同)

Cai*_*von 7

>>> def cmp(a, b):
...     return [c for c in a if c.isalpha()] == [c for c in b if c.isalpha()]
... 
>>> cmp('Hai, this is a test', 'Hai ! this is a test')
True
>>> cmp('Hai, this is a test', 'Hai this is a test')
True
>>> cmp('Hai, this is a test', 'other string')
False
Run Code Online (Sandbox Code Playgroud)

这会创建两个临时列表,但不会以任何方式修改原始字符串.

  • 而不是`c in string.letters`,你可以使用`c.isalpha()`. (3认同)