Python Forum
How to compare strings that have spaces
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to compare strings that have spaces
#1
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?
Reply
#2
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
>>> 
hobbyist likes this post
Reply
#3
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.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Trying to understand strings and lists of strings Konstantin23 2 695 Aug-06-2023, 11:42 AM
Last Post: deanhystad
  Splitting strings in list of strings jesse68 3 1,702 Mar-02-2022, 05:15 PM
Last Post: DeaD_EyE
  Can't compare two strings uriel 2 1,624 Dec-04-2021, 05:39 AM
Last Post: uriel
  Finding multiple strings between the two same strings Slither 1 2,477 Jun-05-2019, 09:02 PM
Last Post: Yoriz
  lists, strings, and byte strings Skaperen 2 4,179 Mar-02-2018, 02:12 AM
Last Post: Skaperen
  Compare several strings and output average TotallyCoolGuy 2 2,847 Jan-28-2018, 05:07 PM
Last Post: TotallyCoolGuy

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020