문제

나는 이런 줄을 나누고 싶다

'foofo21'
'bar432'
'foobar12345'

~ 안으로

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

누군가 파이썬에서 쉽고 간단한 방법을 알고 있습니까?

도움이 되었습니까?

해결책

나는 사용하여 이것에 접근 할 것이다 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)

regex를 사용하지 않고 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