我想分割像这样的字符串

'foofo21'
'bar432'
'foobar12345'

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

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

有帮助吗?

解决方案

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

match = re.match(r"([a-z]+)([0-9]+)", 'foofo21', re.I)
if match:
    items = match.groups()
    # items is ("foo", "21")

其他提示

>>> def mysplit(s):
...     head = s.rstrip('0123456789')
...     tail = s[len(head):]
...     return head, tail
... 
>>> [mysplit(s) for s in ['foofo21', 'bar432', 'foobar12345']]
[('foofo', '21'), ('bar', '432'), ('foobar', '12345')]
>>> 
>>> 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')]

又一个选择:

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

我总是提出findall()=)

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

请注意,我使用的是比以前大多数答案更简单(更少打字)的正则表达式。

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)

不使用正则表达式,使用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']
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top