1

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

2
  • 2
    What result exactly do you want to achieve? Commented Aug 4, 2011 at 19:15
  • When you say "join" you mean "string concatenate". "String concatenate set entries". (You could also have meant "set-join", "list-append", etc). Commented Feb 27, 2024 at 4:33

5 Answers 5

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

0

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'

2 Comments

In that case ''.join(sett) is simpler and more efficient.
@Achim: I was getting there. Just needed to triple-check the syntax. :)
0
>>> ''.join(set(['1','2']))
'12'

I guess this is what you want.

Comments

-1

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.

2 Comments

Technically correct. But without an example of the right way to do things, it's not very helpful for Wyatt.
Technically correct. ;-) But when I answered, the question was not formatted at all and I didn't got the idea what he wanted to do at all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.