【问题标题】:How to split strings into text and number?如何将字符串拆分为文本和数字?
【发布时间】:2010-09-30 14:43:31
【问题描述】:

我想拆分这样的字符串

'foofo21'
'bar432'
'foobar12345'

进入

['foofo', '21']
['bar', '432']
['foobar', '12345']

有人知道在 python 中执行此操作的简单方法吗?

【问题讨论】:

    标签: python string split


    【解决方案1】:

    我会通过以下方式使用re.match 来解决这个问题:

    import re
    match = re.match(r"([a-z]+)([0-9]+)", 'foofo21', re.I)
    if match:
        items = match.groups()
    print(items)
    >> ("foofo", "21")
    

    【讨论】:

    • 你可能想要 \w 而不是 [a-z] 和 \d 而不是 [0-9]
    • @Dan:使用 \w 是一个糟糕的选择,因为它匹配所有字母数字字符,而不仅仅是 a-z。因此,整个字符串将被第一组捕获。
    • 如果这是一个问题,您可以在末尾添加 '\b' (IIRC),以指定匹配必须在单词边界处结束(或 '$' 以匹配字符串的结尾)。
    • 如何将其扩展到 str-digit-str-digit 例如 p6max20 以获得 p=6, max=20? “( )( )( )( )”四个分组?
    • re.split('(\d+)', t)
    【解决方案2】:
    >>> def mysplit(s): ... 头 = s.rstrip('0123456789') ... 尾 = s[len(head):] ...返回头部,尾部 ... >>> [mysplit(s) for s in ['foofo21', 'bar432', 'foobar12345']] [('foofo', '21'), ('bar', '432'), ('foobar', '12345')] >>>

    【讨论】:

    • 在我的机器上使用单个示例(案例研究,不代表所有用途)将此答案的时间与accepted answer 进行比较,此str().rstrip() 方法的速度大约快了 4 倍。此外,它不需要再次导入。
    • 更像pythonic。
    • 不知道这有多相关,但是当我尝试 FOO_BAR10.34 时,它给了我“FOO_BAR10”。和 '34' 然后当我将 mysplits 重新应用于第一个元素时,它给了我同样的东西。我知道我的问题略有不同。
    • 但我可以切片“FOO_BAR10”。删除“。”,然后重新应用该功能以获得我想要的。 +1。
    • 要在末尾拆分 'float' 添加 '.' rstrip() 调用中的数字。
    【解决方案3】:

    另一种选择:

    >>> [re.split(r'(\d+)', s) for s in ('foofo21', 'bar432', 'foobar12345')]
    [['foofo', '21', ''], ['bar', '432', ''], ['foobar', '12345', '']]
    

    【讨论】:

    • 整洁。甚至: [re.split(r'(\d+)', s)[0:2] for s in ...] 摆脱那个额外的空字符串。请注意,与 \w 相比,这相当于 [^|\d]。
    • @PEZ:可能不止一对,并且列表开头可能有一个空字符串。您可以使用 [filter(None, re.split(r'(\d+)', s)) for s in ('foofo21','a1')] 删除空字符串
    【解决方案4】:
    >>> r = re.compile("([a-zA-Z]+)([0-9]+)")
    >>> m = r.match("foobar12345")
    >>> m.group(1)
    'foobar'
    >>> m.group(2)
    '12345'
    

    所以,如果您有一个具有该格式的字符串列表:

    import re
    r = re.compile("([a-zA-Z]+)([0-9]+)")
    strings = ['foofo21', 'bar432', 'foobar12345']
    print [r.match(string).groups() for string in strings]
    

    输出:

    [('foofo', '21'), ('bar', '432'), ('foobar', '12345')]
    

    【讨论】:

      【解决方案5】:

      我总是提出 findall() =)

      >>> strings = ['foofo21', 'bar432', 'foobar12345']
      >>> [re.findall(r'(\w+?)(\d+)', s)[0] for s in strings]
      [('foofo', '21'), ('bar', '432'), ('foobar', '12345')]
      

      请注意,我使用的正则表达式比之前的大多数答案更简单(键入更少)。

      【讨论】:

      • r'\w' 匹配 ''。我在问题中没有看到“”。
      • 我没有在问题中看到 A-Z。上面写着“文字和数字”。
      • @PEZ:如果你允许除数字之外的任何文本,那么你的正则表达式应该是 r'(\D+)(\d+)'。
      【解决方案6】:

      这是一个简单的函数,可以从任意长度的字符串中分隔多个单词和数字,re 方法只分隔前两个单词和数字。我认为这将在未来对其他人有所帮助,

      def seperate_string_number(string):
          previous_character = string[0]
          groups = []
          newword = string[0]
          for x, i in enumerate(string[1:]):
              if i.isalpha() and previous_character.isalpha():
                  newword += i
              elif i.isnumeric() and previous_character.isnumeric():
                  newword += i
              else:
                  groups.append(newword)
                  newword = i
      
              previous_character = i
      
              if x == len(string) - 2:
                  groups.append(newword)
                  newword = ''
          return groups
      
      print(seperate_string_number('10in20ft10400bg'))
      # outputs : ['10', 'in', '20', 'ft', '10400', 'bg'] 
      

      【讨论】:

        【解决方案7】:

        不使用正则表达式,使用 isdigit() 内置函数,仅当开始部分是文本,后面部分是数字时才有效

        def text_num_split(item):
            for index, letter in enumerate(item, 0):
                if letter.isdigit():
                    return [item[:index],item[index:]]
        
        print(text_num_split("foobar12345"))
        

        输出:

        ['foobar', '12345']
        

        【讨论】:

          【解决方案8】:
          import re
          
          s = raw_input()
          m = re.match(r"([a-zA-Z]+)([0-9]+)",s)
          print m.group(0)
          print m.group(1)
          print m.group(2)
          

          【讨论】:

            【解决方案9】:

            这有点长,但对于字符串中有多个随机放置的数字的情况更通用。此外,它不需要导入。

            def getNumbers( input ):
                # Collect Info
                compile = ""
                complete = []
            
                for letter in input:
                    # If compiled string
                    if compile:
                        # If compiled and letter are same type, append letter
                        if compile.isdigit() == letter.isdigit():
                            compile += letter
                        
                        # If compiled and letter are different types, append compiled string, and begin with letter
                        else:
                            complete.append( compile )
                            compile = letter
                        
                    # If no compiled string, begin with letter
                    else:
                        compile = letter
                    
                # Append leftover compiled string
                if compile:
                    complete.append( compile )
                
                # Return numbers only
                numbers = [ word for word in complete if word.isdigit() ]
                    
                return numbers
            

            【讨论】:

              【解决方案10】:

              这是解决该问题的简单方法,不需要regex

              user = input('Input: ') # user = 'foobar12345'
              int_list, str_list = [], []
              
              for item in user:
               try:
                  item = int(item)  # searching for integers in your string
                except:
                  str_list.append(item)
                  string = ''.join(str_list)
                else:  # if there are integers i will add it to int_list but as str, because join function only can work with str
                  int_list.append(str(item))
                  integer = int(''.join(int_list))  # if you want it to be string just do z = ''.join(int_list)
              
              final = [string, integer]  # you can also add it to dictionary d = {string: integer}
              print(final)
              

              【讨论】:

              • 你确定这是正确的item = int(item) # searching for integers in your string!!!!???
              猜你喜欢
              • 2012-12-30
              • 1970-01-01
              • 2021-11-29
              • 1970-01-01
              • 1970-01-01
              • 2015-11-20
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多