Why str(reversed(…)) doesn't give me the reversed string?

前端 未结 2 2081
情书的邮戳
情书的邮戳 2021-01-04 20:12

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          


        
相关标签:
2条回答
  • 2021-01-04 20:42

    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
    
    0 讨论(0)
  • 2021-01-04 20:50

    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'
    >>> 
    
    0 讨论(0)
提交回复
热议问题