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.

Shubham Srivastava
  • 1,190
  • 14
  • 28
  • 2
    See [*Compare strings in python like the sql “like” (with “%” and “_”)*](http://stackoverflow.com/questions/26148712/compare-strings-in-python-like-the-sql-like-with-and) – Wiktor Stribiżew Dec 05 '16 at 09:52

3 Answers3

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
Pierre Barre
  • 2,174
  • 1
  • 11
  • 23
0

You can use .startswith() method.

if s2.startswith(s1):
    return True

or you may use in operator, as suggested by user312016

abukaj
  • 2,582
  • 1
  • 22
  • 45
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
ettanany
  • 19,038
  • 9
  • 47
  • 63