如何在Python中比较两个字符串仅包含某些字符

24

我有两个字符串要比较,应该返回以下结果

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

或者

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

这里显示我们找不到这个型号名称,但如果你向下滚动,就会看到有 tempo traveller 12str/15str。所以我已经将这两辆出租车列入了寻找 tempo traveller 的搜索结果。


3个回答

9
您可以使用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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接