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.
本文探讨了Python中字符串反转的基本概念与多种实现方法,包括内置方法、使用切片和自定义函数等,旨在提供一种高效且易于理解的反转字符串的解决方案。
|
667
191
| |
|
1381
|
How about:
This is extended slice syntax. It works by doing | ||||||||||||||||||||
|
|
145
|
@Paolo's | ||||||||||||||||||||
|
|
19
|
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:
| ||||||||||||||||
|
|
10
|
Quick Answer (TL;DR)Example
Detailed AnswerBackgroundThis answer is provided to address the following concern from a user odigity:
Problem
Solution
Pitfalls
RationalePython has a special circumstance to be aware of: a string is an iterable type. One rationale for excluding a In simplified terms, this simply means each individual character in a string can be easily operated on as a part of a sequential array of elements, just like arrays in other programming languages. To understand how this works, reviewing example02 can provide a good overview. Example02
ConclusionThe cognitive load associated with understanding how slice notation works in python may indeed be too much for some adopters and developers who do not wish to invest much time in learning the language. Nevertheless, once the basic principles are understood, the power of this approach over fixed string manipulation methods can be quite favorable. For those who think otherwise, there are alternate approaches, such as lambda functions, iterators, or simple one-off function declarations. If desired, a developer can implement her own string.reverse() method, however it is good to understand the rationale behind this "quirk" of python. See also |
402
''.join((s[i] for i in xrange(len(s)-1, -1, -1))). – Dennis Mar 6 '13 at 6:49