将unicode字符串拆分为包含数字和字母的组件

时间:2016-08-01 18:24:41

标签: python regex

我想将字符串u'123K拆分为123K。我已尝试re.match("u'123K", "\d+")匹配数字re.match("u'123K", "K")以匹配字母,但它们不起作用。什么是Pythonic方法呢?

2 个答案:

答案 0 :(得分:2)

使用re.findall()查找所有数字和字符:

>>> s = u'123K'
>>> re.findall(r'\d+|[a-zA-Z]+', s) # or use r'\d+|\D+' as mentioned in comment in order to match all numbers and non-numbers.
['123', 'K']

如果你只是处理这个字符串,或者你只想从最后一个字符中拆分字符串,你可以简单地使用索引:

num, charracter = s[:-1], s[-1:]

答案 1 :(得分:0)

您还可以使用itertools.groupby方法,将数字分组:

MATLAB