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>Writing a function that is more readable and flexible?</p>

<pre><code>def get_string(input_str, step=3):
    output = ""
    i = 0
    for _ in list(input_str):
        if i == len(input_str):
            return output
        elif i+step-1 &gt;= len(input_str):
            output += input[len(input_str)-1:i-1:-1]
            return output
        else:
            output += input_str[i+step-1:i:-1] + input_str[i]
            i += step
    return output
</code></pre>

<p>And here comes the flexible part:</p>

<pre><code>get_string("abcdefghi")
# Ouputs 'cbafedihg'
get_string("abcdefghi", 2)
# Outputs 'badcfehgi'
get_string("abcdefghi", 5)
# Outputs 'edcbaihgf'
</code></pre>

<p>Not to mention, if you want to add some more logic or change the logic, it is easier to change here.</p>

python string python-2.7