Connecting Tech Pros Worldwide Forums | Help | Site Map

Splitting strings

Newbie
 
Join Date: Mar 2008
Posts: 5
#1: Apr 8 '08
I'm doing a program for a class of mine and I am having trouble splitting my strings up. I know you can do something like:

a = '012345'
a[0:3]
returns 012

but I am inputing strings of varying length and I cant just do the above notation. I need to split the string into groups of 3 in order to work. Any help would be much appreciated.

Expert
 
Join Date: Sep 2007
Posts: 856
#2: Apr 8 '08

re: Splitting strings


You can use that notation, you just need to use a loop and probably the range function (docs here in the Python Library Reference). Or you could use the slice function from the same source.
Expert
 
Join Date: Apr 2006
Posts: 512
#3: Apr 8 '08

re: Splitting strings


Expand|Select|Wrap|Line Numbers
  1. >>> import textwrap
  2. >>> s="123456"
  3. >>> textwrap.wrap(s,3)
  4. ['123', '456']
  5.  
bvdet's Avatar
Moderator
 
Join Date: Oct 2006
Location: Nashville, TN
Posts: 1,566
#4: Apr 8 '08

re: Splitting strings


Expand|Select|Wrap|Line Numbers
  1. >>> import string
  2. >>> s = string.ascii_letters+string.digits
  3. >>> n=3
  4. >>> [s[i:i+n] for i in range(0,len(s),n)]
  5. ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqr', 'stu', 'vwx', 'yzA', 'BCD', 'EFG', 'HIJ', 'KLM', 'NOP', 'QRS', 'TUV', 'WXY', 'Z01', '234', '567', '89']
  6. >>> 
Newbie
 
Join Date: Mar 2008
Posts: 5
#5: Apr 10 '08

re: Splitting strings


thanks guys that all helped a lot. The help was much appreciated.
Reply