Reverse characters of string in subset of 3
<p>Let say my string is as:</p>

<pre><code>x = 'abcdefghi'
</code></pre>

<p>I want to reverse it in subsets of 3, so that my output is:</p>

<pre><code>x = 'cbafedihg'
</code></pre>

<p>i.e. 0th index is swapped with 2nd index, 3rd index swapped with 5th, and so on.</p>

<p>Below is my code based on converting the <code>string</code> to <code>list</code> and swap the elements within the list:</p>

<pre><code>string_list = list(x)
for i in range(len(string_list)/3):
    string_list[i*3], string_list[i*3+2] = string_list[i*3+2], string_list[i*3]

''.join(string_list)
# Output: 'cbafedihg'
</code></pre>

<p>I want to know what will be the most efficient and most pythonic way to  achieve it. </p>

<p>Note: <code>len(x)%3</code> will always be 0.</p>

<p>Simply swap the elements of list with step as 3:</p>

<pre><code>&gt;&gt;&gt; string_list = list(x)
&gt;&gt;&gt; string_list[::3], string_list[2::3] = string_list[2::3], string_list[::3]
&gt;&gt;&gt; ''.join(string_list)
'cbafedihg'
</code></pre>

python string python-2.7