There is no built in reverse
function in Python's str
object. What is the best way of implementing this?
If supplying a very concise answer, please elaborate on it's efficiency. Is the str
converted to a different object, etc.
How about:
This is extended slice syntax. It works by doing |
|||||||||||||||||||||
|
@Paolo's |
|||||||||||||||||||||
|
Attempting a canonical answer for this question:
While Much faster is using a reverse slice:
But how can we make this more readable and understandable to someone less familiar with the intent of the original author? Let's create a named slice object, and pass it to the subscript notation.
Implement as Function To actually implement this as a function, I think it is semantically clear enough to simply use a descriptive name:
And usage is simply:
Demo of timings (differences are probably exacerbated by the shortness of the string being reversed):
And for the function:
|
|||||||||
|
|
|||
|
|
|||||||||
|
Reverse a string in python without using reversed() or [::-1]
|
|||
|
Thank you for your interest in this question.
Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.
Would you like to answer one of these unanswered questions instead?
''.join((s[i] for i in xrange(len(s)-1, -1, -1)))
. – Dennis Mar 6 '13 at 6:49