如何在Python中将集合元素添加到字符串中

发布于 2024-11-27 18:02:46 字数 170 浏览 1 评论 0原文

如何将集合元素添加到 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

对你而言 2024-12-04 18:02:46

我相信你想要这个:

s = set(['1', '2'])

asString = ''.join(s)

请注意,集合不像列表那样排序。它们通常会按照添加的顺序排列,直到删除某些内容为止,但顺序可能与您添加它们的顺序不同。

I believe you want this:

s = set(['1', '2'])

asString = ''.join(s)

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.

梦巷 2024-12-04 18:02:46

字符串是不可变的。

elements.join(i) 不会更改 elements。您需要将 join 返回的值分配给某些内容:

s = set(['1', '0'])
elements = ''
for i in s:
    elements = elements.join(i)

但是,正如其他人指出的那样,这更好:

s = set(['1', '0'])
elements = ''
elements = elements.join(s)

或者以最简洁的形式:

s = set(['1', '0'])
elements = ''.join(s)

Strings are immutable.

elements.join(i) does not change elements. You need to assign the value returned by join to something:

s = set(['1', '0'])
elements = ''
for i in s:
    elements = elements.join(i)

But, as others pointed out, this is better still:

s = set(['1', '0'])
elements = ''
elements = elements.join(s)

or in its most concise form:

s = set(['1', '0'])
elements = ''.join(s)
橘香 2024-12-04 18:02:46

这应该可行:

sett = set(['1', '0'])
elements = ''
for i in sett:
    elements += i
# elements = '10'

但是,如果您只是想获取每个元素的字符串表示形式,您可以简单地执行以下操作:

elements = ''.join(sett)
# elements = '10'

This should work:

sett = set(['1', '0'])
elements = ''
for i in sett:
    elements += i
# elements = '10'

However, if you're just looking to get a string representation of each element, you can simply do this:

elements = ''.join(sett)
# elements = '10'
养猫人 2024-12-04 18:02:46
>>> ''.join(set(['1','2']))
'12'

我想这就是你想要的。

>>> ''.join(set(['1','2']))
'12'

I guess this is what you want.

捎一片雪花 2024-12-04 18:02:46

不知道“向字符串添加集合元素”是什么意思。但无论如何:字符串在 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文