如何在Python中将集合元素添加到字符串中
如何将集合元素添加到 python 中的字符串中?我尝试过:
sett = set(['1', '0'])
elements = ''
for i in sett:
elements.join(i)
但没有骰子。当我打印元素时,字符串为空。帮助
how would I add set elements to a string in python? I tried:
sett = set(['1', '0'])
elements = ''
for i in sett:
elements.join(i)
but no dice. when I print elements the string is empty. help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我相信你想要这个:
请注意,集合不像列表那样排序。它们通常会按照添加的顺序排列,直到删除某些内容为止,但顺序可能与您添加它们的顺序不同。
I believe you want this:
Be aware that sets are not ordered like lists are. They'll be in the order added typically until something is removed, but the order could be different than the order you added them.
字符串是不可变的。
elements.join(i)
不会更改elements
。您需要将join
返回的值分配给某些内容:但是,正如其他人指出的那样,这更好:
或者以最简洁的形式:
Strings are immutable.
elements.join(i)
does not changeelements
. You need to assign the value returned byjoin
to something:But, as others pointed out, this is better still:
or in its most concise form:
这应该可行:
但是,如果您只是想获取每个元素的字符串表示形式,您可以简单地执行以下操作:
This should work:
However, if you're just looking to get a string representation of each element, you can simply do this:
我想这就是你想要的。
I guess this is what you want.
不知道“向字符串添加集合元素”是什么意思。但无论如何:字符串在 Python 中是不可变的,所以你不能向它们添加任何内容。
Don't know what you mean with "add set elements" to a string. But anyway: Strings are immutable in Python, so you cannot add anything to them.