0

I have the following set in python (its actually one set item):

  product_set = {'Product, Product_Source_System, Product_Number'} 

I want to add a static prefix (source.) to all the comma seperated values in the set, so I get the following output:

 {'source.Product, source.Product_Source_System, source.Product_Number'} 

I tried with a set comprehension, but it doesn't do the trick or I'm doing something wrong. It only prefixes the first value in the set.

{"source." + x for x in set}

I know sets are immutable. I don't need a new set, just output the new values.

Anyone that can help?

Thanks in advance

2
  • 1
    Can't reproduce. The prefix is added to all elements, as expected. (Also don't call your sets set - it hides the set builtin.) Commented Aug 12, 2022 at 12:07
  • Ahhh my bad, it appears I have quite a weird set, with one big comma seperated value. I've changed my starting post Commented Aug 12, 2022 at 12:14

2 Answers 2

3

Edit: Splitting the initial long string into a list of short strings and then (only if required) making a set out of the list:

s1 = set('Product, Product_Source_System, Product_Number'.split(', '))

Constructing a new set:

s1 = {'Product', 'Product_Source_System', 'Product_Number'}
s2 = {"source." + x for x in s1}

Only printing the new strings:

for x in s1:
    print("source." + x)
Sign up to request clarification or add additional context in comments.

2 Comments

Thx for the swift response, I've made a mistake in the starting post and I've edited it.
I've updated the initial response
2

Note: The shown desired result is a new set with updated comma-seperated values. Further down you mentioned: "I don't need a new set, just output the new values". Which one is it? Below an option to mimic your desired result:

import re

set =  {'Product, Product_Source_System, Product_Number'}
set = {re.sub(r'^|(,\s*)', r'\1source.', list(set)[0])}
# set = {'source.'+ list(set)[0].replace(', ', ', source.')}
print(set)

Prints:

{'source.Product, source.Product_Source_System, source.Product_Number'}

3 Comments

either works for me, but your solution returns an error unfortunately. Thanks for the help though
@JVGBI, please note the greyed out option without Regex.
Works like a flaw, thank you so much! :)

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.