英文:
what happens behind an example of a reverse string program?
问题
我朋友让我通过反转字符串来改变它,显然反转字符串只会给你对象ID,我设法找到了一种方法来做到这一点,但我不理解代码下面发生了什么。我不明白的部分是join()
如何与一个反转后的值一起工作,当反转后的值会在使用join()
之前转换成列表或元组吗?我没有明确要将字符串更改为列表,那么代码的哪一部分执行了这种更改?
a = 'apple'
b = '1'.join(reversed(a))
print(b)
英文:
so my friend tasked me with changing a string by reversing it, obviously reversing a string gives you just the object id, i managed to find a way to do it but i dont understand what happens under the code. The part i dont get is how join() works with a reversed value, does a value when reversed get converted into a list or tuple before using the join? i didnt clarify to change the string into a list, so what part of the code carries over that change?
a = 'apple'
b = '1'.join(reversed(a))
print(b)
答案1
得分: 1
你误解了调用 reversed
函数时发生的情况:
>>> a = 'apple'
>>> reversed(a)
<reversed object at 0x000002119BDDA3E0>
reversed()
并没有给你一个 "对象标识"。对象标识是你在该对象上调用 id()
时得到的:
>>> id(reversed(a))
2274652699040
reversed()
给你一个特殊的迭代器对象(既不是列表也不是元组),该对象会颠倒你传递给它的内容。这个对象没有实现一个漂亮的 __repr__
方法,这就是为什么如果你尝试将它原样打印到控制台,你会得到默认的 <CLASS object at ADDRESS>
字符串表示。但是你可以像对待其他迭代器一样对待它。
例如,你可以遍历它:
>>> for i in reversed(a):
... print(i)
...
e
l
p
p
a
你可以将它转换为一个 list
:
>>> list(reversed(a))
['e', 'l', 'p', 'p', 'a']
你可以将它作为参数传递给 str.join
:
>>> ''.join(reversed(a))
'elppa'
英文:
You're misunderstanding what's going on when you call the reversed
function:
>>> a = 'apple'
>>> reversed(a)
<reversed object at 0x000002119BDDA3E0>
reversed()
isn't giving you an "object id". The object id is what you'd get if you called id()
on that object:
>>> id(reversed(a))
2274652699040
reversed()
is giving you a special iterator object (which is neither a list nor a tuple) that reverses whatever you passed into it. This object doesn't implement a nice __repr__
method, which is why you get the default <CLASS object at ADDRESS>
string representation if you just try to print it to the console as-is, but you can do anything with it that you can do with any other iterator.
For example, you can loop over it:
>>> for i in reversed(a):
... print(i)
...
e
l
p
p
a
you can turn it into a list
:
>>> list(reversed(a))
['e', 'l', 'p', 'p', 'a']
and you can pass it as an argument to str.join
:
>>> ''.join(reversed(a))
'elppa'
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论