我有可选数字和字母的字符串,例如'01a','b'和'02'。这些字符串总是有两个部分,左边是数字,右边是字母。我想拆分这些字符串以分别获取数字和字母。如何定义mySplit
以获得此结果?
>>> map(mySplit, ['01123absd', 'bsdf', '02454'])
[('01123', 'absd'), (None, 'bsdf'), ('02454', None)]
答案 0 :(得分:2)
与jramirez的答案类似,只是缩短了一点:
def myFunction(s):
return (''.join(c for c in s if c.isdigit()) or None,
''.join(c for c in s if c.isalpha()) or None)
print map(myFunction, ['01123absd', 'bsdf', '02454', '012abc345def'])
输出:
[('01123', 'absd'), (None, 'bsdf'), ('02454', None), ('012345', 'abcdef')]
答案 1 :(得分:2)
您可以使用正则表达式。我们想要的是:
请注意,regex
将创建命名组,每次时, 也会编译 。
import re
regex = re.compile("^(?P<numbers>\d*)(?P<letters>\w*)$")
def myFunction(entry):
(numbers, letters) = regex.search(entry).groups()
return (numbers or None, letters or None)
map(myFunction, ['01123absd', 'bsdf', '02454'])
最后一行的调用给出了以下输出:
[('01123', 'absd'), (None, 'bsdf'), ('02454', None)]
答案 2 :(得分:1)
如果您不想使用正则表达式,这是一个解决方案:
def split_num_str(my_str):
num = [x for x in my_str if x.isdigit()]
num = "".join(num)
if not num:
num = None
my_str = [x for x in my_str if x.isalpha()]
my_str = ''.join(my_str)
if not my_str:
my_str = None
return num, my_str
m = map(split_num_str, ['01123absd', 'bsdf', '02454'])
print m
result = [('01123', 'absd'), (None, 'bsdf'), ('02454', None)]
答案 3 :(得分:1)
您可以在此处使用正则表达式:
import re
def myFunction(numbers_and_letters):
m = re.match(r"([a-z]*)([0-9]*)", numbers_and_letters)
return tuple(v == "" and None or v for v in m.groups())
答案 4 :(得分:0)
import re
def myFunction(t):
m = re.match(r"([a-z]*)([0-9]*)", t)
x,y = m.groups()
if x=='': x= None
if y=='': y= None
return ((x,y))
for s in ['01123absd', 'bsdf', '02454']:
print myFunction(s)
产生
(None, '01123')
('bsdf', None)
(None, '02454')