8. String reversal

Use slicing to reverse a string instead of building it character by character.

Slicing communicates reversal as one operation instead of as an algorithm implemented by the loop. That is shorter, easier to trust, and usually the first form experienced Python readers expect to see.

8.1. Don’t do this

1name = 'one-off coder'
2name = ''.join([name[i] for i in range(len(name) - 1, -1, -1)])

8.2. Do this

Use slicing to reverse a string. The first number is the start index, the second is the stop index, and the last is the step. Here, the start and stop values are omitted, and the step is -1, which moves backward through the string.

1name = 'one-off coder'
2name = name[::-1]

We can also print just even-indexed characters backwards.

1name = 'one-off coder'
2name = name[0::2][::-1]

We can also print just odd-indexed characters backwards.

1name = 'one-off coder'
2name = name[1::2][::-1]