-1

Possible Duplicates:
Split python string every nth character?
What is the most “pythonic” way to iterate over a list in chunks?

I need to split a string into equal parts. For example, if I have this string:

string = "123456781234567812345678"

I need to cut every 8 characters:

["12345678", "12345678", "12345678"]
Community
  • 1
  • 1
user1656145
  • 21
  • 1
  • 2

2 Answers2

7

This is actually a great application for a python list comprehension one-liner!

my_str="123456781234567812345678"
splits=[my_str[x:x+8] for x in range(0,len(my_str),8)]
//splits = ["12345678","12345678","12345678"]

Let me know if you have any questions.

Sean Johnson
  • 5,567
  • 2
  • 17
  • 22
-6

This might help:

str.split(str="", num=string.count(str)).

str: any delimeter, by default it is space.

num: number of lines to be made.

You can get more info here.

Tim Post
  • 33,371
  • 15
  • 110
  • 174
  • This doesn't answer the question, which is about splitting into strings of a given length rather than by a delimiter – David Robinson Sep 08 '12 at 04:53
  • 2
    It's nice that you did a search to help the question author, but simply copying the first result you find without any explanation (even with citation) really isn't helping. The OP might just use `8` for the delimiter and think it works. – Tim Post Sep 08 '12 at 04:54