Python Forum

Full Version: How to compare strings that have spaces
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I want to compare two strings and check if they are the same. For example, this string:

"This is a sentence"

with this:

" This is a sentence "

As can be seen they are not to the same since the last sentence has before and after the sentence spaces. How do I do this kind of comparisons?
Use the strip() method
if string1.strip() == string2.strip():
    do_something()
If you also want to take into account the inner spaces, you can achieve this with the re module
>>> import re
>>> a = "This   is a   sentence\t that says foo     bar   "
>>> b = "   This is    a sentence      that   says  foo\t        bar" 
>>> 
>>> def norm(s):
...     return re.sub(r"\s+", " ", s.strip())
... 
>>> norm(a)
'This is a sentence that says foo bar'
>>> norm(b)
'This is a sentence that says foo bar'
>>> norm(a) == norm(b)
True
>>> a == b
False
>>> 
What appears to be a problem? As you stated, they are not the same and simple string comparison with == will confirm it and return False.