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'
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.
>>> 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']
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With