I want to compare two strings such that the comparison should ignore differences in the special characters. That is,
Hai, this is a test
Should match with
Hai ! this is a test "or" Hai this is a test
Is there any way to do this without modifying the original strings?
We can simply compare them while ignoring the spaces using the built-in replaceAll() method of the String class: assertEquals(normalString. replaceAll("\\s+",""), stringWithSpaces. replaceAll("\\s+",""));
Remove Special Characters From the String in Python Using the str. isalnum() Method. The str. isalnum() method returns True if the characters are alphanumeric characters, meaning no special characters in the string.
Using 'str.replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.
This removes punctuation and whitespace before doing the comparison:
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
Generally, you'd replace the characters you wish to ignore, and then compare them:
import re
def equal(a, b):
# Ignore non-space and non-word characters
regex = re.compile(r'[^\s\w]')
return regex.sub('', a) == regex.sub('', b)
>>> equal('Hai, this is a test', 'Hai this is a test')
True
>>> equal('Hai, this is a test', 'Hai this@#)($! i@#($()@#s a test!!!')
True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With