i have list of strings:
x = ['+27', '05', '1995 f']
i want code outputs this:
['+', '27', '05', '1995', 'f']
i thinking using .split()
function on last element wrote code:
x=['+27', '05', '1995 f'] x[2]=x[2].split()
this outputs:
['+27', '05', ['1995', 'f']]
how ensure 2nd element not sub-list, , instead output this?
['+27', '05','1995','f']
should use insert
, del
?
i wrote first element using insert
, 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 better way?
here's solution using itertools.groupby()
, str.isdigit()
in list comprehension:
>>> itertools import groupby >>> x=['+27', '05', '1995 f'] >>> [''.join(g).strip() s in x k, g in groupby(s, str.isdigit)] ['+', '27', '05', '1995', 'f']
this works splitting each string in x
groups of characters based on whether they're digits or not, joining groups strings, , stripping whitespace resulting strings.
as can see, unlike other solutions presented far, splits '+27' '+' , '27' (as question says want).