By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,035 Members | 1,995 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,035 IT Pros & Developers. It's quick & easy.

Splitting strings

P: 5
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.
Apr 7 '08 #1
Share this Question
Share on Google+
4 Replies


Expert 100+
P: 849
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.
Apr 8 '08 #2

Expert 100+
P: 511
Expand|Select|Wrap|Line Numbers
  1. >>> import textwrap
  2. >>> s="123456"
  3. >>> textwrap.wrap(s,3)
  4. ['123', '456']
  5.  
Apr 8 '08 #3

bvdet
Expert Mod 2.5K+
P: 2,851
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. >>> 
Apr 8 '08 #4

P: 5
thanks guys that all helped a lot. The help was much appreciated.
Apr 9 '08 #5

Post your reply

Sign in to post your reply or Sign up for a free account.