Why doesn't str (reverse (...)) give me the return line?

I'm trying to get used to iterators. Why if I print

b = list(reversed([1,2,3,4,5])) 

This will give me a reverse list, but

 c = str(reversed('abcde')) 

won't give me the return line?

+5
source share
2 answers

In Python, reversed actually returns a reverse iterator. Thus, list applied to the iterator will provide you with a list object.

In the first case, the input was also a list, so you liked the result of the list applied on the reversed iterator.

In the second case, str applied to the returned iterator object will actually provide you with a string representation.

Instead, you need to iterate over the values ​​in the iterator and connect them to str.join , like this

 >>> ''.join(reversed('abcde')) edcba 
+9
source

in another way, use the method to stretch a slice . more details

 >>> a = "abcde" >>> a[::-1] 'edcba' >>> 

line by line to list β†’ list back β†’ list of connections

 >>> a 'abcde' >>> b = list(a) >>> b ['a', 'b', 'c', 'd', 'e'] >>> b.reverse() >>> b ['e', 'd', 'c', 'b', 'a'] >>> "".join(b) 'edcba' >>> 
+4
source

Source: https://habr.com/ru/post/1213814/


All Articles