如何在python中比较两个字符串和一些字符
我有两个字符串要比较,下面的结果应该会返回如何在python中比较两个字符串和一些字符,python,string,Python,String,我有两个字符串要比较,下面的结果应该会返回 s1 = 'toyota innova' s2 = 'toyota innova 7' if s1 like s2 return true 或 那么,我如何在python中进行比较? 例如。 这表明我们找不到该型号名称,但如果向下滚动,则会显示tempo Traveler 12str/15str。因此,我展示了这两辆出租车来搜索tempo Traveler。您可以使用中的来检查另一辆出租车中是否包含字符串: 'toyota innova' i
s1 = 'toyota innova'
s2 = 'toyota innova 7'
if s1 like s2
return true
或
那么,我如何在python中进行比较?
例如。
这表明我们找不到该型号名称,但如果向下滚动,则会显示tempo Traveler 12str/15str。因此,我展示了这两辆出租车来搜索tempo Traveler。您可以使用中的
来检查另一辆出租车中是否包含字符串:
'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
您可以使用.startswith()
方法
if s2.startswith(s1):
return True
或者您可以在
操作符中使用,正如用户312016所建议的那样您可能还需要检查s1中的s2是否如下所示:
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
看见
>>> s1 = "test1"
>>> s2 = "test1 test2"
>>>
>>> my_cmp(s1, s2)
True
>>>
>>> s3 = "test1 test2"
>>> s4 = "test1"
>>>
>>> my_cmp(s3, s4)
True