Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 373
Rohith Avatar asked May 10 '13 03:05

Rohith


People also ask

How do you compare strings to ignore spaces?

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+",""));

How do you exclude a special character in Python?

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.

How do you remove spaces and special characters from a string in Python?

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.


2 Answers

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
like image 93
root Avatar answered Oct 15 '22 22:10

root


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
like image 35
Dan Lecocq Avatar answered Oct 15 '22 21:10

Dan Lecocq