【问题标题】:How to check if one string ends with another, or the other way around?如何检查一个字符串是否以另一个字符串结尾,或者相反?
【发布时间】:2012-11-17 19:07:13
【问题描述】:

给定两个字符串,如果其中一个字符串出现在另一个字符串的末尾,则返回 True,忽略大小写差异(换句话说,计算不应“区分大小写”)。

示例/测试:

>>> end_other('Hiabc', 'abc') 
True 
>>> end_other('AbC', 'HiaBc') 
True 
>>> end_other('abc', 'abXabc') 
True

我的代码:

def end_other(s1, s2):
    
    s1 = s1.upper()
    s2 = s2.upper()
    
    if s1[2:6] == s2:
        return True
    elif s2[2:6] == s1:
        return True
    elif s2 == s1:
        return True    
    else:
        return False

我的预期是错误的。

(注意:这是来自CodingBat的代码实践

【问题讨论】:

    标签: python python-3.x string


    【解决方案1】:

    有什么原因你不能使用内置函数?

    def end_other(s1, s2):
        s1 = s1.upper()
        s2 = s2.upper()
        return s1.endswith(s2) or s2.endswith(s1)
    

    带有任意切片的代码没有多大意义。

    【讨论】:

      【解决方案2】:

      类似这样的东西,使用str.rfind():

      In [114]: def end(s1,s2):
          s1=s1.lower()
          s2=s2.lower()
          if s1 in s2 and s2.rfind(s1)+len(s1) == len(s2):
              return True
          elif  s2 in s1 and s1.rfind(s2)+len(s2) == len(s1):
              return True 
          return False
         .....: 
      
      In [115]: end('Hiabc','abc')
      Out[115]: True
      
      In [116]: end('abC','HiaBc')
      Out[116]: True
      
      In [117]: end('abc','abxabc')
      Out[117]: True
      
      In [118]: end('abc','bc')
      Out[118]: True
      
      In [119]: end('ab','ab12')
      Out[119]: False
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-08-23
        • 2010-10-13
        • 2022-03-31
        • 2013-05-12
        相关资源
        最近更新 更多