python - 如何仅在python中比较两个字符串与某些字符

标签 python string

<分区>

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

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 traveler 12str/15str。所以我展示了这两辆出租车来寻找节奏旅行者。

最佳答案

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

关于python - 如何仅在python中比较两个字符串与某些字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40971392/

相关文章:

python - 如何使用字符串引用类的实例?

c - 在c中使用分隔符分割字符串

python ,Seaborn : how to replicate corrplot?

Python ConfigParser.NoSectionError : No section:

python - 有没有办法在 matplotlib 箱线图图例中标记均值和中值?

c - 我自己的 strcpy 函数

静态 c 函数可以返回本地 char 数组吗?

python - 如何使用 ftplib 在远程服务器上创建 .txt 文件并使用变量在其中放置一些字符串?

python - 如何在 python 中使 print 语句成为一行?

c# - .NET/C# - 将 char[] 转换为字符串