Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string into strings by length?

Tags:

python

Is there a way to take a string that is 4*x characters long, and cut it into 4 strings, each x characters long, without knowing the length of the string?

For example:

>>>x = "qwertyui" >>>split(x, one, two, three, four) >>>two 'er' 
like image 662
tkbx Avatar asked Dec 02 '12 19:12

tkbx


People also ask

How do I split a string into multiple strings?

split() The method split() splits a String into multiple Strings given the delimiter that separates them. The returned object is an array which contains the split Strings. We can also pass a limit to the number of elements in the returned array.


2 Answers

>>> x = "qwertyui" >>> chunks, chunk_size = len(x), len(x)//4 >>> [ x[i:i+chunk_size] for i in range(0, chunks, chunk_size) ] ['qw', 'er', 'ty', 'ui'] 
like image 198
Alexander Avatar answered Sep 20 '22 00:09

Alexander


I tried Alexanders answer but got this error in Python3:

TypeError: 'float' object cannot be interpreted as an integer

This is because the division operator in Python3 is returning a float. This works for me:

>>> x = "qwertyui" >>> chunks, chunk_size = len(x), len(x)//4 >>> [ x[i:i+chunk_size] for i in range(0, chunks, chunk_size) ] ['qw', 'er', 'ty', 'ui'] 

Notice the // at the end of line 2, to ensure truncation to an integer.

like image 33
fnkr Avatar answered Sep 21 '22 00:09

fnkr