Splitting a string

Terry Reedy tjreedy at udel.edu
Fri Apr 2 11:05:50 EDT 2010


On 4/2/2010 6:21 AM, Shashwat Anand wrote:
>  >>> s = 'si_pos_99_rep_1_0.ita'
>  >>> res = tuple(re.split(r'(\d+)', s))
>  >>> res
> ('si_pos_', '99', '_rep_', '1', '_', '0', '.ita')

This solves the core of the problem, but is not quite there ;-).
Thomas requested conversion of int literals to ints, which is easy:

import re
s = 'si_pos_99_rep_1_0.ita'
res = re.split(r'(\d+)', s)
for i,s in enumerate(res):
   try: res[i] = int(s)
   except: pass
res = tuple(res)
print(res)

('si_pos_', 99, '_rep_', 1, '_', 0, '.ita')

Terry Jan Reedy



> On Fri, Apr 2, 2010 at 3:42 PM, Thomas Heller <theller at ctypes.org
> <mailto:theller 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')




More information about the Python-list mailing list