我想比较两个字符串,以便比较应忽略特殊字符的差异.那是,
海,这是一个考验
应该配合
海!这是一个测试"或"海这是一个测试
有没有办法在不修改原始字符串的情况下执行此操作?
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)
>>> 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)
这会创建两个临时列表,但不会以任何方式修改原始字符串.