【问题标题】:How to extract a specific symbols from string if they follow after the number如果它们跟随在数字之后,如何从字符串中提取特定符号
【发布时间】:2014-09-04 23:09:26
【问题描述】:

我需要从字符串中提取一个或多个符号@。我只需要那些一个接一个且不被任何字符和空格分隔的符号。 符号或多个符号@ 应紧跟在数字之后。如果不是,则应忽略符号并且不返回。

我只需要从字符串a 提取三个@@@ 符号,因为第四个符号用空格字符分隔。

a='some text 1 a8 777@@@ @ more text here 123 456`

结果是:

@@@

从变量b 函数将返回None,因为在一个或多个数字之后没有一个符号@。

b='some text @@@ @ more text here 123 456`

从c 变量只返回一个符号@,因为它是唯一跟在数字后面的符号(并且没有与它们分开):

c='some text @@@ 777@ more text here 123 456`

结果:@

【问题讨论】:

  • 我相信这个问题会得到回答,因为它很容易获得代表,但是......你试过什么?你研究过正则表达式吗?

标签: python string


【解决方案1】:

您可以为此使用正则表达式:

>>> import re
>>> r = re.compile(r'\d(@+)')
>>> a = 'some text 1 a8 777@@@ @ more text here 123 456'
>>> r.search(a).group(1)
'@@@'
>>> b = 'some text @@@ @ more text here 123 456'
>>> r.search(b) #None
>>> c = 'some text @@@ 777@ more text here 123 456'
>>> r.search(c).group(1)
'@'

将它与if 条件结合起来检查正则表达式是否匹配字符串中的任何内容:

>>> m = r.search(c)
>>> if m:
    print m.group(1)

@

【讨论】:

    【解决方案2】:

    虽然可能有一个正则表达式来执行此操作,但如果您不知道什么是正则表达式,则循环更容易理解。

    i = 0
    found = False
    while i < len(string) and not found:
      if i != 0 and string[i] == '@':
        if string[i-1].isnumeric():
          found = True
        else:
          i+=1
      else:
        i+=1
    
    if not found:
      return None
    else:
      out = ''
      while string[i] == '@':
        out += '@'
        i+=1
      return out
    

    也许可以重写得更好,但这是一种简单的方法。

    脚注:不过,正则表达式会更好。

    【讨论】:

      【解决方案3】:
      import re
      
      print re.findall('[0-9]@+', a)
      

      这将打印一个包含所有匹配项的列表,在上述情况下它将打印

      ['7@@@']
      

      现在你可以对字符串进行切片,得到你想要的。

      希望这会有所帮助!

      【讨论】:

        【解决方案4】:

        这对你有用吗?

        >>> import re
        >>> re.search('\d(@+)', a).groups()[0]
        '@@@'
        >>> re.search('\d(@+)', b)
        >>> re.search('\d(@+)', c).groups()[0]
        '@'
        

        【讨论】:

          猜你喜欢
          • 2022-08-10
          • 1970-01-01
          • 2019-07-22
          • 2021-10-30
          • 2017-07-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多