简体   繁体   中英

String searching and comparison in Python

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

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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM