【问题标题】:How to compare two string with some characters only in python [duplicate]如何仅在python中将两个字符串与某些字符进行比较[重复]
【发布时间】:2017-04-19 16:15:07
【问题描述】:

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

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

【问题讨论】:

标签: python string


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    if s2.startswith(s1):
        return True
    

    或者您可以使用 in 运算符,如 user312016 建议的那样

    【讨论】:

      【解决方案3】:

      您可能还需要像这样检查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
      

      【讨论】:

        猜你喜欢
        • 2021-07-10
        • 2016-07-08
        • 1970-01-01
        • 1970-01-01
        • 2013-01-20
        • 2017-06-30
        • 2016-08-29
        • 2021-03-04
        • 1970-01-01
        相关资源
        最近更新 更多