0

I have to add string --foo to each element in given set and been trying hard to do that but unable to do. Is it really possible to do that? Below is the set

a = {"apple", "banana", "cherry", "6363738", "1"}

output

a = {"apple--foo", "banana--foo", "cherry--foo", "6363738-foo", "1-foo"}

4 Answers 4

6

You can use string concatenation in a set comprehension

>>> {i+'--foo' for i in a}
{'banana--foo', '6363738--foo', 'apple--foo', 'cherry--foo', '1--foo'}
Sign up to request clarification or add additional context in comments.

Comments

3

You can try

a = {"apple", "banana", "cherry", "6363738", "1"}
{"{}--foo".format(i) for i in a}

or for Python 3.6 and above

{f"{i}--foo" for i in a}

Output

{"apple--foo", "banana--foo", "cherry--foo", "6363738-foo", "1-foo"}

2 Comments

That right for Python 3.6 and higher but for lower versions format will be better.
One would hope that pre-3.6 deployments are diminishing rapidly.
0

Several ways to accomplish this, here is a simple for loop:

for i in range(len(a)):
    a[i] += "--foo"

2 Comments

This just adds an additional set element "--foo" for each existing element; it does not append --foo to each element of the set. (Nor would item += "--foo", because str values are immutable.)
That was a typo, but you are correct. Fixed it now.
0

For a change, using lambda:

>>> map(lambda x: x + '--foo', a)

OUTPUT:

>>> set(map(lambda x: x + '--foo', a)) # {'apple--foo', '6363738--foo', '1--foo', 'cherry--foo', 'banana--foo'}                                                                                                       

Comments

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.