24

I have two strings to compare and the following result should return

s1 = 'toyota innova'
s2 = 'toyota innova 7'
if s1 like s2
   return true

OR

s1 = 'tempo traveller'
s2 = 'tempo traveller 15 str'  //or tempo traveller 17 str
if s1 like s2
    return true

So, how this I compare in python? for eg. getmecab.com/round-trip/delhi/agra/tempo-traveller

In this it is showing that we don't find this model name but if you scroll down there is tempo traveller 12str/15str showing. so I have show these two cabs in search of tempo traveller.

1

3 Answers 3

9

You could use in to check if a string is contained in an other:

'toyota innova' in 'toyota innova 7' # True
'tempo traveller' in 'tempo traveller 15 str' # True

If you only want to match the start of the string, you can use str.startswith:

'toyota innova 7'.startswith('toyota innova') # True
'tempo traveller 15 str'.startswith('tempo traveller') # True

Alternatively, if you only want to match the end of the string, you can use str.endswith

'test with a test'.endswith('with a test') # True
Sign up to request clarification or add additional context in comments.

Comments

0

You can use .startswith() method.

if s2.startswith(s1):
    return True

or you may use in operator, as suggested by user312016

Comments

0

You may also need to check if s2 in s1 like this:

def my_cmp(s1, s2):
    return (s1 in s2) or (s2 in s1)

Output:

>>> s1 = "test1"
>>> s2 = "test1 test2"
>>>
>>> my_cmp(s1, s2)
True
>>>
>>> s3 = "test1 test2"
>>> s4 = "test1"
>>>
>>> my_cmp(s3, s4)
True

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.