[Tutor] Splitting long string into same len parts

Alan Gauld alan.gauld at freenet.co.uk
Thu Feb 9 10:45:52 CET 2006


Hi Victor,

> I'd like to split a long string into equally long strings (len(str) =
> 3). I did the following using regexes:

> This is what I needed. Is there an easier or more straightforward way to
> do this?

Define easier :-)

You could just use string slicing and a stepsize of 3 in range:

lst = []
for index in range(0,len(mystring),3):
     lst.append(mystring[index : index+3])

Or tutrning that into a comprehension

lst = [mystring[index : index+3] for index in range(0,len(mystring),3)]

is that easier? I'm, not sure... and you still have problems where the 
string is not exactly divisible by 3, should you add padding?

HTH,

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld




More information about the Tutor mailing list