Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two string with some characters only in python [duplicate]

Tags:

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.

like image 209
Shubham Srivastava Avatar asked Dec 05 '16 09:12

Shubham Srivastava


People also ask

How do you compare two strings partially in Python?

Use the in operator for partial matches, i.e., whether one string contains the other string. x in y returns True if x is contained in y ( x is a substring of y ), and False if it is not. If each character of x is contained in y discretely, False is returned.

How do you compare strings up to certain characters?

strcmp is used to compare two different C strings. When the strings passed to strcmp contains exactly same characters in every index and have exactly same length, it returns 0. For example, i will be 0 in the following code: char str1[] = "Look Here"; char str2[] = "Look Here"; int i = strcmp(str1, str2);

How do I check if two characters are the same in Python?

Python strings equality can be checked using == operator or __eq__() function. Python strings are case sensitive, so these equality check methods are also case sensitive.

How would you confirm that 2 strings have the same identity in Python?

How would you confirm that 2 strings have the same identity? The is operator returns True if 2 names point to the same location in memory. This is what we're referring to when we talk about identity. Don't confuse is with ==, the latter which only tests equality.


1 Answers

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
like image 159
Pierre Barre Avatar answered Oct 14 '22 11:10

Pierre Barre