There is no built in reverse
function for Python's str
object. What is the best way of implementing this method?
If supplying a very concise answer, please elaborate on its efficiency. For example, whether the str
object is converted to a different object, etc.
Quick Answer (TL;DR)
Example
Detailed Answer
Background
This answer is provided to address the following concern from @odigity:
Problem
Solution
Pitfalls
string.reverse()
string.reverse()
to avoid slice notation.print 'coup_ate_grouping'[-4:] ## => 'ping'
print 'coup_ate_grouping'[-4:-1] ## => 'pin'
print 'coup_ate_grouping'[-1] ## => 'g'
[-1]
may throw some developers offRationale
Python has a special circumstance to be aware of: a string is an iterable type.
One rationale for excluding a
string.reverse()
method is to give python developers incentive to leverage the power of this special circumstance.In simplified terms, this simply means each individual character in a string can be easily operated on as a part of a sequential arrangement of elements, just like arrays in other programming languages.
To understand how this works, reviewing example02 can provide a good overview.
Example02
Conclusion
The 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 aspect of python.
See also
All of the above solutions are perfect but if we are trying to reverse a string using for loop in python will became a little bit tricky so here is how we can reverse a string using for loop
I hope this one will be helpful for someone.
Recursive method:
example:
You can use the reversed function with a list comprehesive. But I don't understand why this method was eliminated in python 3, was unnecessarily.