我有这样的字符串; ’17.’,’0,5′,’,5′,’CO2-heidet’,’1990ndatel’等我想把它们分成如下:[’17’,’.’],[‘0′ ,’,’,’5′],[‘,’,’5′],[‘CO’,’2′,’-heidet’],[‘1990′,’ndatel’]等.
我怎么能在python中有效地做到这一点?
最佳答案 这是
re.split
的一种方式:
In [1]: import re
In [2]: def split_digits(s):
...: return [g for g in re.split(r'(\d+)', s) if g]
...:
In [3]: for s in ['17.', '0,5', ',5', 'CO2-heidet', '1990ndatel']:
...: print(repr(s), 'becomes', split_digits(s))
...:
'17.' becomes ['17', '.']
'0,5' becomes ['0', ',', '5']
',5' becomes [',', '5']
'CO2-heidet' becomes ['CO', '2', '-heidet']
'1990ndatel' becomes ['1990', 'ndatel']