0

Im trying to create somthing which splits a string into a block of 4 characters. So lets say it obtains the string: "HELLOWORLDIAMAROBOT"

it would then format it to:

HELL
OWOR
LDIA
MARO
BOT

Thanks

Tersosauros
  • 883
  • 1
  • 12
  • 22
Caudy19
  • 21
  • 1
  • 2
  • related: [What is the most “pythonic” way to iterate over a list in chunks?](http://stackoverflow.com/q/434287/4279) – jfs Apr 04 '16 at 03:12
  • 1
    Where are you stuck? What specific issue do you have? What have you tried? Show us your code and the output that it produces (mention how it is different from the expected output), include a complete traceback if there are exceptions. – jfs Apr 04 '16 at 03:14

2 Answers2

4

This is one way to do it.

string = "HELLOWORLDIAMAROBOT"

def split_string(string, split_string):
    return [string[i:i+split_string] for i in range(0, len(string), split_string)]

print (split_string(string,4))

Output:

['HELL', 'OWOR', 'LDIA', 'MARO', 'BOT']
Joe T. Boka
  • 6,554
  • 6
  • 29
  • 48
1

This can be done in a one-liner:

[string[i:i+4] for i in range(0, len(string), 4)]

As you can see both here and here.

Community
  • 1
  • 1
Tersosauros
  • 883
  • 1
  • 12
  • 22