我想比较两个字符串,这样比较应该忽略特殊字符的差异。也就是说,
Hai, this is a test
应该匹配
Hai ! this is a test "or" Hai this is a test
有没有办法在不修改原始字符串的情况下做到这一点?
最佳答案
这会在进行比较之前删除标点符号和空格:
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
关于 python : How to compare strings and ignore white space and special characters,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16474848/