Splitting a string
Alex Willmer
alex at moreati.org.uk
Fri Apr 2 06:44:01 EDT 2010
On Apr 2, 11:12 am, Thomas Heller <thel... at ctypes.org> wrote:
> Maybe I'm just lazy, but what is the fastest way to convert a string
> into a tuple containing character sequences and integer numbers, like this:
>
> 'si_pos_99_rep_1_0.ita' -> ('si_pos_', 99, '_rep_', 1, '_', 0, '.ita')
>
This is very probably not the fastest execution wise, it was the
fastest development time wise:
import re
def maybe_int(x):
try:
return int(x)
except ValueError:
return x
def strings_n_ints(s):
return tuple(maybe_int(x) for x in re.findall('(\d+|\D+)', s))
>>> strings_n_ints('si_pos_99_rep_1_0.ita')
('si_pos_', 99, '_rep_', 1, '_', 0, '.ita')
Alex
More information about the Python-list
mailing list