Well, this is technically a way to invalidate your function, but either the built in slicing operator or the reversed
function would do this for you in one line:
"flash"[::-1]
>>> "hsalf"
The slice operator takes three parameters, where it starts and ends, but also what step to take as it increments. You could pass in 2 to get every second letter, but you can also pass in a negative value to start at the end and work backwards, hence reversing your string.
The reversed
function can take any iterator and return it in reverse as a generator object. This means that it wont strictly print properly, ie. this is what you would get when printing it:
reversed("flash")
>>> <reversed object at 0x0000000002F50898>
But calling join with it will give the result you need:
''.join(reversed("flash"))
>>> "hsalf"
Note that as erip points out this can have trouble with unicode characters in Python 2. In 3 all strings are unicode, but not before then. So reversing non unicode strings actually messes up the byte order, causing erratic behaviour like this:
>>> print("mañana"[::-1])
ana±am
To safely avoid this in 2, make sure to declare it as unicode with a u
before the string u"mañana"
. This will make either method work fine. Alternatively from __future__ import unicode_literals
will make all strings unicode like they are in Python 3.
But for your approach I'll still give suggestions. You use a slightly complicated approach. Swapping the values at opposite ends is not entirely obvious so I'd recommend adding comments to elaborate a bit on what the intent is as code is not always readable on its own.
Also you could use Python's multiple assignment to clean up some code. A more simple example is your begin and end could be set at the same time:
begin, end = 0, len(string) - 1
This doesn't add a lot but can look a little neater. It essentially lets you assign two variables at once. It might be unnecessary, but the same principle can be used to eliminate the need for your temp
.
strlist[end], strlist[begin] = strlist[begin], strlist[end]
This allows you to safely assign both at the same time. The right hand side of the expression is fully evaluated before any assignment, so you wont lose either value.