Python3.5.2反向方法字符串


>>> x = "hello world"
>>> y = reversed(x)
>>> z = ''.join(y)
>>> z
'dlrow olleh'
>>> y
<reversed object at 0x7f2871248b38>
>>> ''.join(y)
''
>>> x
'hello world'
>>> ''.join(y)
''
>>> z = ''.join(y)
>>> z
''

为什么我下次将z的值作为空白字符串的值,在逆转函数中加入操作

这是因为反向返回迭代器,当您在其上应用操作时,它会"消耗"元素。如果您想将反向的结果存储在变量中,那么加入是一种很好的方法。

from collections.abc import Iterator
print(isinstance(reversed("hello world"), Iterator)) # True
it = reversed("hello world")
for x in it:
    print(x) # Prints the letters
for x in it:
    print(x) # Do not print them, there are already "consumed"