Reputation: 3781
I have such strings; '17.'
, '0,5'
, ',5'
, 'CO2-heidet'
, '1990ndatel'
, etc. I want to split them as follows: ['17', '.'], ['0', ',', '5'], [',', '5'], ['CO', '2', '-heidet'], ['1990', 'ndatel']
, etc.
How can I do this efficiently in python?
Upvotes: 3
Views: 100
Reputation: 48092
You may also use itertools.groupby()
with key as str.isdigit
to achieve this as:
>>> from itertools import groupby
>>> my_list = ['17.', '0,5', ',5', 'CO2-heidet', '1990ndatel']
>>> [[''.join(j) for i, j in groupby(l, str.isdigit)] for l in my_list]
[['17', '.'], ['0', ',', '5'], [',', '5'], ['CO', '2', '-heidet'], ['1990', 'ndatel']]
Upvotes: 4
Reputation: 65791
Here's a way with 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']
Upvotes: 3