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.