开发者

How to add set elements to a string in python

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. w开发者_JAVA百科hen I print elements the string is empty. help


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.


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)


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'


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

I guess this is what you want.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜