8

I have this situation: I got a string that I want to split every X characters. My problem is that the split method only splits the string based on a string such as:

a = 'asdeasxdasdqw'
print a.split('x')

>>>['asdeasx', 'dasdqw']

What I need is something similar to:

[pseudocode]

paragraph = 'my paragraph'

split_offset = 4
print paragraph.split(split_offset)

>>> ['my pa', 'ragraph']
Arthur Silva
  • 150
  • 1
  • 2
  • 11

1 Answers1

25

This is called slicing:

>>> paragraph[:5], paragraph[5:]
('my pa', 'ragraph')

To answer the "split every X characters" question, you would need a loop:

>>> x = 5
>>> [paragraph[i: i + x] for i in range(0, len(paragraph), x)]
['my pa', 'ragra', 'ph']

There are more solutions to this though, see:

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195