为什么str(reversed(...))没有给我反向字符串? [英] Why str(reversed(...)) doesn't give me the reversed string?

查看:101
本文介绍了为什么str(reversed(...))没有给我反向字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图习惯于迭代器.为什么输入

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?

推荐答案

在Python中, reversed 实际上返回一个反向迭代器.因此,应用于迭代器的 list 会为您提供列出对象.

In Python, reversed actually returns a reverse iterator. So, list applied on the iterator will give you the list object.

在第一种情况下,输入也是一个列表,因此将list的结果应用于reversed迭代器似乎对您来说合适.

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

在第二种情况下, str 应用于返回的迭代器对象实际上将为您提供它的字符串表示形式.

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

这篇关于为什么str(reversed(...))没有给我反向字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆