>>> line = '1234567890'
>>> n = 2
>>> [line[i:i+n] for i in range(0, len(line), n)]
['12', '34', '56', '78', '90']
Answer from satomacoto on Stack Overflow>>> line = '1234567890'
>>> n = 2
>>> [line[i:i+n] for i in range(0, len(line), n)]
['12', '34', '56', '78', '90']
Just to be complete, you can do this with a regex:
>>> import re
>>> re.findall('..','1234567890')
['12', '34', '56', '78', '90']
For odd number of chars you can do this:
>>> import re
>>> re.findall('..?', '123456789')
['12', '34', '56', '78', '9']
You can also do the following, to simplify the regex for longer chunks:
>>> import re
>>> re.findall('.{1,2}', '123456789')
['12', '34', '56', '78', '9']
And you can use re.finditer if the string is long to generate chunk by chunk.
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 string into chunks at keyword(s), while preserving spacing and conditions of what words to split at? - Stack Overflow
python - How to split a string into different lengthed chunks? - Stack Overflow
Is there a way to split a string into chunks and store in a list python - Stack Overflow
What is the most Pythonic way to split a string into chunks
Can I use regular expressions to split strings into variable-sized chunks
Is there a built-in Python function for splitting strings into segments
Heya,
What I'm looking to do is split a text every x-amount of words. For instance, let's say I have a 300 word string and I want to split it into three chunks. Currently, I'm using:
chunks = text.split(' ')[:100]However, this just splits the first 100 words into one chunk. What would be the best way to either have this loop through the text in a way that gives me a few different lists, or otherwise makes the list elements each 100 words?
Hope this request makes sense. I've search for an answer for this and feel like I might be using the wrong words to describe my problem, which is why I'm yet to find an answer.
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.
>>> s = '25c319f75e3fbed5a9f0497750ea12992b30d565'
>>> n = [8, 4, 4, 4, 4, 12]
>>> print '-'.join([s[sum(n[:i]):sum(n[:i+1])] for i in range(len(n))])
Output
25c319f7-5e3f-bed5-a9f0-4977-50ea12992b30
Create an iterator from the string and slice incrementally using itertools.islice:
from itertools import islice
s = '25c319f75e3fbed5a9f0497750ea12992b30d565'
it = iter(s)
n = [8, 4, 4, 12]
s = '-'.join(''.join(islice(it, None, x)) for x in n)
print(s)
# 25c319f7-5e3f-bed5-a9f0497750ea
Note that the trailing part of the string is lost if the total size of the slice(s) does not equal the length of the string; iterator is not completely exhausted.
You may append the trailing part (if needed) in a final preprocessing stage:
s += '-' + ''.join(it)
print(s)
# 25c319f7-5e3f-bed5-a9f0497750ea-12992b30d565
Here's another approach that uses a for loop, slicing the string incrementally by increasing the start index:
start = 0
d = []
for i in n:
d.append(s[start:start+i])
start += i
d.append(s[start:])
print('-'.join(d))
# 25c319f7-5e3f-bed5-a9f0497750ea-12992b30d565
You can use x[start_index:end_index] which yields a substring from x (last index excluded). So just specify 2 positions and use them e.g.:
a = len(x) // 3
b = 2* len(x) // 3
s0 = x[:a]
s1 = x[a:b]
s2 = x[b:]
You can make use of the split function in python
word = 'yfbrtutcfyugytfytfytcfdycfyrcdtrdrcdtreextredydsadyradrydstrdfrdfrrdecrcxhx'
x=round(len(word)/3)
print([word[i:i+x] for i in range(0, len(word),x)])
And it gives you:
['yfbrtutcfyugytfytfytcfdyc', 'fyrcdtrdrcdtreextredydsad', 'yradrydstrdfrdfrrdecrcxhx']
Hello again...
I'm back with another problem that's probably simple to fix but I'm dumb lol. I'm trying to splice a long string of hexadecimals into smaller sections for a better visual output. The problem is it only uses the first 32 characters then just repeats that input to all the strings.How would I get the function to continue onto the next 32 characters until the end of the string? Is there a way to just remove the first section after each passthrough?
Code:
# Raw hex string (512chars | 256bytes | 1byte == 2chars)
# Note: "XX" is supposed to be in printed line 2
raw = '000102030405060708090A0B0C0D0E0FXX0102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F'
# Converted byte strings (32chars/16bytes per line)
line = []
def hex_extract(s):
i = 0
for x in s:
# Split chunk into 16bytes
chunk = ([s[i:i+2] for i in range(0, 32, 2)])
# Append chunk to converted list
line.append(chunk)
for x in line:
# Print all lines (only reprints the first line :sad_face:
print(f'[{i+1}]\t| ',*line[i], sep=' ', end='\n')
i += 1
# Call function
hex_extract(raw)If you'd like to access a string 3 characters at a time, you're going to need to use slicing.
You can get a list of the 3-character long pieces of the string using a list comprehension like this:
>>> x = 'this is a string'
>>> step = 3
>>> [x[i:i+step] for i in range(0, len(x), step)]
['thi', 's i', 's a', ' st', 'rin', 'g']
>>> step = 5
>>> [x[i:i+step] for i in range(0, len(x), step)]
['this ', 'is a ', 'strin', 'g']
The important bit is:
[x[i:i+step] for i in range(0, len(x), step)]
range(0, len(x), step) gets us the indices of the start of each step-character slice. for i in will iterate over these indices. x[i:i+step] gets the slice of x that starts at the index i and is step characters long.
If you know that you will get exactly four pieces every time, then you can do:
a, b, c, d = [x[i:i+step] for i in range(0, len(x), step)]
This will happen if 3 * step < len(x) <= 4 * step.
If you don't have exactly four pieces, then Python will give you a ValueError trying to unpack this list. Because of this, I would consider this technique very brittle, and would not use it.
You can simply do
x_pieces = [x[i:i+step] for i in range(0, len(x), step)]
Now, where you used to access a, you can access x_pieces[0]. For b, you can use x_pieces[1] and so on. This allows you much more flexibility.
You can use unpacking
a,b,c,d=x.split(' ');
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
CHUNK = 4
[a[i*CHUNK:(i+1)*CHUNK] for i in xrange((len(a) + CHUNK - 1) / CHUNK )]
python pydash package could be a good choice.
from pydash.arrays import chunk
ids = ['22', '89', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '1']
chunk_ids = chunk(ids,5)
print(chunk_ids)
# output: [['22', '89', '2', '3', '4'], ['5', '6', '7', '8', '9'], ['10', '11', '1']]
for more checkout pydash chunk list