python : How to compare strings and ignore white space and special characters

标签 python python-3.x string python-2.7 replace

我想比较两个字符串,这样比较应该忽略特殊字符的差异。也就是说,

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/

相关文章:

python - 一行作业与多行作业有什么区别

c++ - std::string s1 {"Modern C++", 3} 与 std::string s1 {str, 3}

java - 从字符串中删除字母

python - 使用 numpy.save (和 savez)出现意外类型错误

linux - 我如何检查 if 和大于 linux 中的条件?

python - Linux结合两个不同的文本文件

python - 在 GUI 内打开指南

python - For 循环中的整个字符串,而不仅仅是逐个字符

python - 如何在Python3中同时进行并行输入和输出?

Python 如何在导入包时模拟 ImportError