I'm trying to get used to iterators. Why if I type
b = list(reversed([1,2,3,4,5]))
It will give me a reversed list, but
c = str(reversed('abcde'))
won't give me a reversed string?
Strings can be reversed using slicing. To reverse a string, we simply create a slice that starts with the length of the string, and ends at index 0. The slice statement means start at string length, end at position 0, move with the step -1 (or one step backward).
reverse() works like reversing the string in place. However, what it actually does is create a new string containing the original data in reverse order.
The reversed() method computes the reverse of a given sequence object and returns it in the form of a list.
In Python, reversed
actually returns a reverse iterator. So, list
applied on the iterator will give you the list object.
In the first case, input was also a list, so the result of list
applied on the reversed
iterator seemed appropriate to you.
In the second case, str
applied on the returned iterator object will actually give you the string representation of it.
Instead, you need to iterate the values in the iterator and join them all with str.join
function, like this
>>> ''.join(reversed('abcde'))
edcba
another way by extend slice method. more details
>>> a = "abcde"
>>> a[::-1]
'edcba'
>>>
by string to list --> list reverse --> join list
>>> a
'abcde'
>>> b = list(a)
>>> b
['a', 'b', 'c', 'd', 'e']
>>> b.reverse()
>>> b
['e', 'd', 'c', 'b', 'a']
>>> "".join(b)
'edcba'
>>>
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