I have this list of strings:
x = ['+27', '05', '1995 F']
I want some code that outputs this:
['+', '27', '05', '1995', 'F']
I was thinking about using the .split()
function on the last element so I wrote this code:
x=['+27', '05', '1995 F']
x[2]=x[2].split()
This outputs:
['+27', '05', ['1995', 'F']]
How do ensure the 2nd element is not a sub-list, and instead output this?
['+27', '05','1995','F']
Should I use insert
and del
?
I wrote this for the first element using insert
and del
:
x=x.split("/")
x.insert(0,x[0][0])
x.insert(1,x[1][1:])
del x[2]
This outputs:
['+', '27', '05', '1995 F']
Is there a better way?
Here's a solution using itertools.groupby()
and str.isdigit()
in a list comprehension:
>>> from itertools import groupby
>>> x=['+27', '05', '1995 F']
>>> [''.join(g).strip() for s in x for k, g in groupby(s, str.isdigit)]
['+', '27', '05', '1995', 'F']
This works by splitting each string in x
into groups of characters based on whether they're digits or not, then joining those groups back into strings, and finally stripping whitespace from the resulting strings.
As you can see, unlike the other solutions presented so far, it splits '+27' into '+' and '27' (as your question says you want).