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.
String class does not have reverse() method, we need to convert the input string to StringBuffer, which is achieved by using the reverse method of StringBuffer.
Python includes a built-in function that is used to create a reverse iterator: the reversed() function. This iterator works because strings are indexed, so each value in a string can be accessed individually. The reverse iterator is then used to iterate through the elements in a string in reverse order.
for i in my_string: Now, since we are iterating, we will be using the iterating variable. We will concatenate the empty string str with the value of an iterating variable which will reverse the string one letter at a time. By end of the for loop, str will contain the given string in reverse order.
How about:
>>> 'hello world'[::-1] 'dlrow olleh'
This is extended slice syntax. It works by doing [begin:end:step]
- by leaving begin and end off and specifying a step of -1, it reverses a string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With