2016-12-05 44 views
4

我有兩個字符串比較和下面的結果應該返回如何只在python

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 

因此,與某些字符比較兩個字符串,如何我在python比較?例如 。 getmecab.com/round-trip/delhi/agra/tempo-traveller

在此顯示,我們沒有找到此型號的名稱,但如果向下滾動速度旅行者12str/15str顯示。所以我已經展示了這兩個出租車尋找節奏旅行者。

+2

見[*比較python中的字符串,如sql像」(與‘%’和‘_’)*](http://stackoverflow.com/questions/26148712/compare-strings-in-python-like-the-sql-like-with-and) –

回答

7

你可以使用in檢查一個字符串包含在其他:

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

如果你只想字符串的開始匹配,你可以使用str.startswith

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

或者,如果您只想匹配字符串的末尾,則可以使用str.endswith

'test with a test'.endswith('with a test') # True 
0

您可以使用.startswith()方法。

if s2.startswith(s1): 
    return True 

,或者您可以使用in運營商,通過user312016

0

的建議,您可能還需要檢查if s2 in s1這樣的:

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

輸出:

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