Reversing a String Using reversed()
In this lesson, you’ll learn how to reverse a string using the
reversed() built-in function.
reversed() is a built-in function which returns an iterator that yields sequence items in reverse order. In this context, an iterator refers to any object which implements the magic method
While implementations of this method are left to the user, calls to it are generally expected to return the next item in a given sequence in some logical order. For example, let’s take a string and turn it into an iterator by using the built-in
iter() function. If you do this for the string
"Hello" and then call
.__next__() repeatedly, you’ll get the characters in a sequential order.
.join() is a method implemented for string objects in Python, which can take in any iterable and concatenate it using the string object as a separator. For example, if you pass the list of strings
"c"] to the method
.join(), called from the string object comprised only of the character
"+", you would get back the string
Recall that the string method takes in any iterable comprised of string objects and that the function
reversed() returns an iterator that yields string objects when applied to a string.
.join() can be called directly on the iterator returned by the function
reversed() to reverse your string.
Become a Member to join the conversation.