a = '123asdad'
str(reversed(a))
>> '<reversed object at 0x00000206C9F80250>'
list(reversed(a))
>> ['d', 'a', 'd', 's', 'a', '3', '2', '1']
I already know that the best way is a[::-1].
But I want to know why I can't convert the reversed object into a str() function. list() or tuple() is possible, but why not str()?
All three are iterable objects and Seqence type objects, is there anything I don't know?
All three are iterable objects and Seqence type objects, is there anything I don't know?
You're correct, they're all iterable objects, but they each have a different implementation of __str__.
If you expect str(reversed(a)) to return "['d', 'a', 'd', 's', 'a', '3', '2', '1']", then what you're essential asking is for the reversed class to have the same behaviour of __str__ as list.
This would actually be quite confusing, because it would blur the distinction between objects of reversed and list. They're intentionally different. A reversed object wraps an underlying collection and behaves as if it had reversed all the elements in memory, without actually wasting CPU/memory to reverse all the elements in memory.
If you do want the list behaviour of __str__, then use it:
str(list(reversed(a)))
Of course, you should notice that this ends up doing all the reversing for real, copying the elements into a new list in the reversed order. If that's undesirable, then you'll have to implement your own formatting code to iterate a reversed object (or any iterable, really), quoting its elements, joining them with , and surrounding them with [ ].
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