python - Iterating over a list and joining items of same type -
i have bunch of strings shoved lists via list(string)
:
stringy = "i've 24got 697love-a-ly2 bunch of 000coconuts!" listy = list(stringy)
where listy
looks like:
['i', "'", 'v', 'e', ' ', '2', '4', 'g', 'o', 't', ' ', 'a', ' ', '6', '9'...
i'm looking cleaner way iterate through list and, without throwing out of individual character entries, join of integers produce:
['i', "'", 'v', 'e', ' ', '24', 'g', 'o', 't', ' ', 'a', ' ', '697','l','o'...
where integers going in strings not predictable, , number of digits in number not predictable (i run 1 or 1000000000.)
to find integer values in first place thought like:
for in listy: if i.isdigit(): x = listy.index(i) z = listy[x+1] if z.isdigit():
...but that's going inefficient bloody mess.
actually putting numbers going pretty easy having trouble coming neat way check each number. suggestions?
you can pretty using re
,
>>> import re >>> = "i've 24got 697love-a-ly2 bunch of 000coconuts!" >>> re.findall(r'\d+|.', a) ['i', "'", 'v', 'e', ' ', '24', 'g', 'o', 't', ' ', 'a', ' ', '697', 'l', 'o', 'v', 'e', '-', 'a', '-', 'l', 'y', '2', ' ', 'b', 'u', 'n', 'c', 'h', ' ', 'o', 'f', ' ', '000', 'c', 'o', 'c', 'o', 'n', 'u', 't', 's', '!']
if doing operation multiple times should consider compiling like,
>>> splitter = re.compile(r'\d+|.')
Comments
Post a Comment