Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you'd like to access a string 3 characters at a time, you're going to need to use <a href="https://stackoverflow.com/a/509295/600110">slicing</a>.</p> <p>You can get a list of the 3-character long pieces of the string using a list comprehension like this:</p> <pre><code>&gt;&gt;&gt; x = 'this is a string' &gt;&gt;&gt; step = 3 &gt;&gt;&gt; [x[i:i+step] for i in range(0, len(x), step)] ['thi', 's i', 's a', ' st', 'rin', 'g'] &gt;&gt;&gt; step = 5 &gt;&gt;&gt; [x[i:i+step] for i in range(0, len(x), step)] ['this ', 'is a ', 'strin', 'g'] </code></pre> <p>The important bit is:</p> <pre><code>[x[i:i+step] for i in range(0, len(x), step)] </code></pre> <p><code>range(0, len(x), step)</code> gets us the indices of the start of each <code>step</code>-character slice. <code>for i in</code> will iterate over these indices. <code>x[i:i+step]</code> gets the slice of <code>x</code> that starts at the index <code>i</code> and is <code>step</code> characters long.</p> <p>If you know that you will get <em>exactly</em> four pieces every time, then you can do:</p> <pre><code>a, b, c, d = [x[i:i+step] for i in range(0, len(x), step)] </code></pre> <p>This will happen if <code>3 * step &lt; len(x) &lt;= 4 * step</code>.</p> <p>If you don't have exactly four pieces, then Python will give you a <code>ValueError</code> trying to unpack this list. Because of this, I would consider this technique very brittle, and would not use it.</p> <p>You can simply do</p> <pre><code>x_pieces = [x[i:i+step] for i in range(0, len(x), step)] </code></pre> <p>Now, where you used to access <code>a</code>, you can access <code>x_pieces[0]</code>. For <code>b</code>, you can use <code>x_pieces[1]</code> and so on. This allows you much more flexibility.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload