Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Split string in a certain length

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']
like image 450
Arthur Silva Avatar asked Apr 12 '16 13:04

Arthur Silva


People also ask

How do you split a string at a specific position in Python?

Python String | split() separator : This is a delimiter. The string splits at this specified separator. If is not provided then any white space is a separator. maxsplit : It is a number, which tells us to split the string into maximum of provided number of times.


1 Answers

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:

  • Split python string every nth character?
  • What is the most "pythonic" way to iterate over a list in chunks?
like image 64
alecxe Avatar answered Oct 27 '22 08:10

alecxe