【问题标题】:How to access the first character and integer pair in a Python string?如何访问 Python 字符串中的第一个字符和整数对?
【发布时间】:2019-05-05 08:28:30
【问题描述】:

我在 Python 中有几个字符串。假设每个字符串都与一个变量相关联。这些字符串仅由字符和整数组成:

one = '74A76B217C'
two = '8B7A1742B'
three = '8123A9A8B'

我想在我的代码中检查这些字符串是否首先存在“A”,如果存在,则返回整数。

所以,在上面的例子中,第一个整数和第一个字符是:对于one、74 和A;对于two、8 和B;对于three、8123 和A。

对于函数,one 将返回 True,而 74; two 为 False,three 为 8123 和 A。

我的问题是,我不确定如何有效地解析字符串以检查第一个整数和字符。

在 Python 中,有一些方法可以检查字符串中是否存在字符,例如

if 'A' in one:
    print('contains A')

但这并没有考虑顺序。访问第一个字符和第一个整数的最有效方法是什么,或者至少检查字符串中出现的第一个字符是否具有某种身份?

【问题讨论】:

  • five = 'A123BCD' 和 six = 'A1A2A3' 会发生什么
  • @mtrw 整数总是第一位的。

标签: python string parsing


【解决方案1】:

您可以使用正则表达式:

>>> re.match('^([0-9]+)A', string)

例如:

import re

for s in ['74A76B217C', '8B7A1742B', '8123A9A8B']:
    match = re.match('^([0-9]+)A', s)
    print(match is not None and match.group(1))

【讨论】:

    【解决方案2】:

    使用regex:^(\d+)A

    import re
    
    def check_string(s):
        m_test = re.search("^(\d+)A", s)
        if m_test:
            return m_test.group(1)
    

    查看在线正则表达式测试器: https://regex101.com/r/LmSbly/1

    【讨论】:

      【解决方案3】:

      试试这个作为正则表达式的替代:

      def check(s):
          i = s.find('A')
          if i > 0 and s[:i].isdigit():
              return int(s[:i]), True
          return False
      
      # check(one) (74, True)
      # check(two) False
      # check(three) (8123, True)
      

      【讨论】:

        【解决方案4】:

        试试正则表达式。

        >>> import re
        >>> re.search('[0-9]+', '74A76B217C').group(0)
        '74'
        >>> re.search('[A-z]', '74A76B217C').group(0)
        'A'
        

        【讨论】:

          猜你喜欢
          • 2011-04-20
          • 2018-08-29
          • 2012-12-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多