How to compare strings that have spaces - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: How to compare strings that have spaces (/thread-31999.html) |
How to compare strings that have spaces - hobbyist - Jan-14-2021 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? RE: How to compare strings that have spaces - Gribouillis - Jan-14-2021 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 >>> RE: How to compare strings that have spaces - perfringo - Jan-14-2021 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.
|