【问题标题】:Is there more 'pythonic' way to do that?有没有更多的“pythonic”方式来做到这一点?
【发布时间】:2019-08-03 01:37:34
【问题描述】:

例如,我们需要编写一个函数来查找字符串中的第一个'@',并返回由@ 之后的0 个或多个字母字符组成的子字符串,因此'xx@abc$$' 返回'abc'。如果不存在@,则返回空字符串。

我是这样解决的,但有没有更 Pythonic 的方法来做到这一点?

def func(s):
    at = s.find('@')
    if at == -1:
        return ''
    end = at + 1
    while end < len(s) and s[end].isalpha():
        end += 1
    return s[at+1:end]

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    你可以使用regex:

    import re
    def func(s):
        r = re.search(r'@([A-Za-z]+)', s)
        return r.group(1) if r else ""
    print(func('xx@abc$$')) # abc
    

    这种模式也适用:

    r = re.search(r'@(\w+)', s)
    

    【讨论】:

      【解决方案2】:
      def func(s):
          # find the @ index
          start_idx = s.find("@")
          # return early if not there
          if start_idx == -1:
              return ""
          # return a string which to it is added the letters that specify criteria
          return "".join([letter for letter in s[start_idx:] if letter.isalpha()])
      

      此函数将返回“@”之后的所有字符并且是字母数字,您没有指定是否只想要第一个非字符。

      【讨论】:

        【解决方案3】:

        您可以使用正则表达式,使用模式 r'@([A-Za-z]+)' 匹配前导 @ 后跟多个字母之一

        import re
        
        def func(s):
        
            pattern = r'@([A-Za-z]+)'
            match = re.search(pattern, s)
        
            #Return match if found else return empty string
            return match.group(1) if match else ''
        
        print(func('xx@abc$$'))
        print(func('xx@abc$$'))
        print(func('xx@ab12$$'))
        print(func('xxabc$$'))
        

        输出将是

        abc
        abc
        ab
        
        

        【讨论】:

          猜你喜欢
          • 2010-12-08
          • 2021-12-20
          • 2011-05-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-04-13
          相关资源
          最近更新 更多