1

I am trying to find matching words in set of two strings using Python. For example string:

a = "Hello Mars"
b = "Venus Hello"

I want to return true/false if the first word in string a equals the second word in string b.

can I do something like this?

if a.[1:] == b.[:] return true else false

1 Answer 1

4

Split the strings using str.split and str.rsplit and then match the first and last word:

>>> a = "Hello Mars"
>>> b = "Venus Hello"
#This compares first word from `a` and last word from `b`.
>>> a.split(None, 1)[0] == b.rsplit(None, 1)[-1]
True

If you only want to compare first and second word then use just str.split.

>>> a.split()
['Hello', 'Mars']
>>> b.split()
['Venus', 'Hello']
#This compares first word from `a` and second word from `b`.
>>> a.split()[0] == b.split()[1]
True

What does str.split and str.rsplit return:

>>> a = "Hello Jupiter Mars"
>>> b = "Venus Earth Hello" 
>>> a.split(None, 1)         #split the string only at the first whitespace
['Hello', 'Jupiter Mars']
>>> b.rsplit(None, 1)        #split the string only at the last whitespace
['Venus Earth', 'Hello']
Sign up to request clarification or add additional context in comments.

1 Comment

+1. Splitting strings into tuples, arrays etc. and working on them can sometimes be 3 times faster than working on strings. While this sounds nice, it of course depends on the problem, and in more complex cases, the benefit may not justify the extra time taken to develop a suitable container-based algorithm for the problem. Choose the right tool for the job.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.