【问题标题】:Using a function in Python to return a substring在 Python 中使用函数返回子字符串
【发布时间】:2013-04-08 21:12:26
【问题描述】:

我觉得我的问题很基础,因为我是第一学期计算机科学专业的学生。

我被要求返回类似于"abcd5efgh" 的字符串中数字之前形成的子字符串。这个想法是使用一个函数给我"abcd"。我想我需要使用.isdigit,但我不确定如何将它变成一个函数。提前谢谢!

【问题讨论】:

    标签: python python-3.x substring


    【解决方案1】:

    可以用正则表达式来完成,但如果你已经发现了isdigit,为什么不在这种情况下使用它呢?

    如果没有找到数字,您可以修改最后return s 行以返回其他内容:

    def string_before_digit(s):
        for i, c in enumerate(s):
            if c.isdigit():
                return s[:i]
        return s # no digit found
    
    print(string_before_digit("abcd5efgh"))
    

    【讨论】:

    • 我刚试过这个,我得到了一个语法错误,突出显示了 string_before_digit。我错过了什么吗?
    • @posthumana 您使用的是 Python 3,请使用 print(...) 而不是 print...
    • 太棒了!我应该知道的。非常感谢。
    【解决方案2】:

    下面的代码将使用正则表达式为您提供第一个非数字部分。

    import re
    myPattern=re.compile('[a-zA-Z]*')
    firstNonDigitPart=myPattern.match('abcd5efgh')
    firstNonDigitPart.group()
    >>> 'abcd'
    

    【讨论】:

      【解决方案3】:

      如果您不允许使用正则表达式,可能是因为他们明确告诉您手动执行,您可以这样做:

      def digit_index(s):
          """Helper function."""
          # next(..., -1) asks the given iterator for the next value and returns -1 if there is none.
          # This iterator gives the index n of the first "true-giving" element of the asked generator expression. True-giving is any character which is a digit.
          return next(
              (n for n, i in enumerate(i.isdigit() for i in "abc123") if i),
              -1)
      
      def before_digit(s):
          di = digit_index(s)
          if di == -1: return s
          return s[:di]
      

      应该会给你想要的结果。

      【讨论】:

      • 你可以返回-1而不是len(s)
      • @jamylak 是的,但是 -1 使该函数与其他搜索功能更兼容,并且可以在其他上下文中使用。以可重用的方式编程也是学习编程的一个重要方面......
      • 你已经在切片了,假设它是一个列表/字符串,所以它现在不是很可重用
      【解决方案4】:

      我目前也是一名学生,这就是我解决这个问题的方法: *对于我的学校,我们不允许在 python 中使用像这样的内置函数:/

           def parse(string):
             newstring = ""
             for i in string:
                if i >= "0" and i <= "9":
                   break
                else:
                   newstring += i
             print newstring #Can use return if your needing it in another function
      
           parse("abcd5efgh")
      

      希望对你有帮助

      【讨论】:

      • 考虑更惯用的if '0' &lt;= i &lt;= '9': 而不是if i &gt;= "0" and i &lt;= "9":
      【解决方案5】:

      一种功能性方法:)

      >>> from itertools import compress, count, imap
      >>> text = "abcd5efgh"
      >>> text[:next(compress(count(), imap(str.isdigit, text)), len(text))]
      'abcd'
      

      【讨论】:

        【解决方案6】:

        一个非常简单的单行,使用isdigit :)

        >>> s = 'abcd5efgh'
        >>> s[:[i for i, j in enumerate([_ for _ in s]) if j.isdigit()][0]]
        'abcd'
        

        【讨论】:

          【解决方案7】:

          一种迭代工具方法:

          >>> from itertools import takewhile
          >>> s="abcd5efgh"
          >>> ''.join(takewhile(lambda x: not x.isdigit(), s))
          'abcd'
          

          【讨论】:

            猜你喜欢
            • 2014-12-07
            • 2017-05-05
            • 2011-12-30
            • 2023-01-17
            • 2014-03-17
            • 1970-01-01
            • 1970-01-01
            • 2013-11-05
            • 2018-03-29
            相关资源
            最近更新 更多