如何用数字和字母分割Python字符串?

2024-09-27 09:35:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我的字符串有可选的数字和字母,例如“01a”、“b”和“02”。这些字符串总是有两部分,数字在左边,字母在右边。我想把这些字符串分开,把数字和字母分开。如何定义mySplit以获得此结果?在

>>> map(mySplit, ['01123absd', 'bsdf', '02454'])

[('01123', 'absd'), (None, 'bsdf'), ('02454', None)]

Tags: 字符串nonemap定义字母数字mysplitbsdf
3条回答

您可以使用正则表达式来执行此操作。我们想要的是:

  • 以0或更多数字开头的字符串
  • 以0个或更多个字母结尾的字符串。在

请注意,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'])

最后一行的调用给出以下输出:

^{pr2}$

如果您不想使用regex,这是一个解决方案:

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

结果=[('01123', 'absd'), (None, 'bsdf'), ('02454', None)]

jramirez answer相似,只是稍微短一点:

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)

仍然使用filter稍微短一点:

^{pr2}$

输出:

print(*map(myFunction, ['01123absd', 'bsdf', '02454', '012abc345def']))
('01123', 'absd') (None, 'bsdf') ('02454', None) ('012345', 'abcdef')

相关问题 更多 >

    热门问题