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"
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.
Python
, write inPython
. – Jared Burrows Aug 28 at 2:50