>>> 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']
Answer from Alexander on Stack Overflow>>> 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']
- :param s: str; source string
- :param w: int; width to split on
Using the textwrap module:
PyDocs-textwrap
import textwrap
def wrap(s, w):
return textwrap.fill(s, w)
:return str:
Inspired by Alexander's Answer
PyDocs-data structures
def wrap(s, w):
return [s[i:i + w] for i in range(0, len(s), w)]
- :return list:
Inspired by Eric's answer
PyDocs-regex
import re
def wrap(s, w):
sre = re.compile(rf'(.{{{w}}})')
return [x for x in re.split(sre, s) if x]
- :return list:
Python Split string in a certain length - Stack Overflow
What's the best way to split a string into fixed length chunks and work with them in Python? - Stack Overflow
python - How to split strings of different lengths? - Stack Overflow
Split string into a list, with items of equal length in python 3 - Stack Overflow
One solution would be to use this function:
def chunkstring(string, length):
return (string[0+i:length+i] for i in range(0, len(string), length))
This function returns a generator, using a generator comprehension. The generator returns the string sliced, from 0 + a multiple of the length of the chunks, to the length of the chunks + a multiple of the length of the chunks.
You can iterate over the generator like a list, tuple or string - for i in chunkstring(s,n):
, or convert it into a list (for instance) with list(generator). Generators are more memory efficient than lists because they generator their elements as they are needed, not all at once, however they lack certain features like indexing.
This generator also contains any smaller chunk at the end:
>>> list(chunkstring("abcdefghijklmnopqrstuvwxyz", 5))
['abcde', 'fghij', 'klmno', 'pqrst', 'uvwxy', 'z']
Example usage:
text = """This is the first line.
This is the second line.
The line below is true.
The line above is false.
A short line.
A very very very very very very very very very long line.
A self-referential line.
The last line.
"""
lines = (i.strip() for i in text.splitlines())
for line in lines:
for chunk in chunkstring(line, 16):
print(chunk)
The standard library offers textwrap.wrap:
from textwrap import wrap
s = "some random text that should be splitted into chunks"
print(wrap(s, width=3))
['som', 'e r', 'and', 'om ', 'tex', 't t', 'hat', 'sho', 'uld', 'be ', 'spl',
'itt', 'ed ', 'int', 'o c', 'hun', 'ks']
Note: the underlying TextWrapper is designed to split text (as in a sentence), not arbitrary sequences of characters. The result is not guaranteed to be a sequence of strings with length == width.
Here's a function that will break a string into c equal size chunks, with the last chunk containing any overflow:
def split_str(strng, c):
l = len(strng) // c
r = [strng[n * l:(n + 1) * l] for n in range(c - 1)]
r.append(strng[(c - 1) * l:])
return r
s = 'Now is the time for all good men to come to the aid'
print(split_str(s, 4))
Result:
['Now is the t', 'ime for all ', 'good men to ', 'come to the aid']
You can simplify the function a bit if you know that the string will always divide evenly. Then it would be just:
def split_str(str, c):
l = len(str) // c
r = [str[n*l:(n+1)*l] for n in range(c)]
The rest is just math, which it sounds like you already have a handle on. Or do you need help finding the factors of a number? I know there are lots of questions about that already on SO.
Here's something a little different that will break the string into as many equally- sized groups as possible and put any excess into an extra one. That won't happen when the length if the string is an exact multiple of the group size.
from itertools import zip_longest
_filler = object() # Value which couldn't be in data.
def grouper(n, iterable):
for result in zip_longest(*[iter(iterable)]*n, fillvalue=_filler):
yield tuple(v for v in result if v is not _filler)
n = 4
s = 'Now is the time for all good men to come to the aid'
group_len = len(s) // n
result = list(''.join(group) for group in grouper(group_len, s))
print(result)
Output
['Now is the t', 'ime for all ', 'good men to ', 'come to the ', 'aid']
split_string_list = [string[x:x+4] for x in range(0,len(string),4)]
Try that
Basically what it is a list generated such that it starts with elements 0-4, then 4-8, etc. which is exactly what you want, typecasted into a string
- There is no attribute
Splitfor strings in any version of python. - If you intended to write
split, the aforementioned method requires a character in all versions of python
python-2.x
>>> string = "abcdefghijklmnopqrstuvwx"
>>> string = string.split(0 - 3)
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
TypeError: expected a character buffer object
python-3.x
>>> string = "abcdefghijklmnopqrstuvwx"
>>> string = string.split(0 - 3)
Traceback (most recent call last):
File "python", line 2, in <module>
TypeError: Can't convert 'int' object to str implicitly
That said...
You can use the following code to split into equal groups:
def split_even(item, split_num):
return [item[i:i+split_num] for i in range(0, len(item), split_num)]
As such:
>>> split_even("abcdefghijklmnopqrstuvwxyz", 4)
['abcd', 'efgh', 'ijkl', 'mnop', 'qrst', 'uvwx', 'yz']
>>> split_even("abcdefghijklmnopqrstuvwxyz", 6)
['abcdef', 'ghijkl', 'mnopqr', 'stuvwx', 'yz']
>>> split_even("abcdefghijklmnopqrstuvwxyz", 13)
['abcdefghijklm', 'nopqrstuvwxyz']
>>>