0

Let's assume I read the following strings out of a file:

s1 = "{'XXX-YYY'}"
s2 = "{'XXX-YYY', 'XXX-ZZZ', 'XXX-AAA', 'XXX-BBB'}"

I want convert both strings to valid sets. I tried this:

s1 = {s1}
s2 = set((s2, ))

The outcome is obviously not a valid set():

{"{'XXX-YYY'}"}
{"{'XXX-YYY', 'XXX-ZZZ', 'XXX-AAA', 'XXX-BBB'}"}

It should be:

{'XXX-YYY'}
{'XXX-YYY', 'XXX-ZZZ', 'XXX-AAA', 'XXX-BBB'}

How can I achieve this?

2
  • Your second set is not valid, it wil only keep 'XXX-YYY' once. Is it what you want? If you want to keep all similar items, you must create a list Commented Oct 9, 2020 at 8:29
  • Sorry, I just added a wrong example, now it should be okay. My problem is obviously the string handling. Commented Oct 9, 2020 at 8:31

2 Answers 2

1

Try this:

s1=s1.replace('{', '').replace('}', '').replace("'", '')
s1=[k.strip() for k in s1.split(',')]
s1=set(s1)

s2=s2.replace('{', '').replace('}', '').replace("'", '')
s2=[k.strip() for k in s2.split(',')]
s2=set(s2)

print(s1)

{'XXX-YYY'}

print(s2)

{'XXX-YYY', 'XXX-AAA', 'XXX-BBB', 'XXX-ZZZ'}
Sign up to request clarification or add additional context in comments.

Comments

1

This will create a set:

def string2set(string):
    unwanted = "{}'"
    for char in unwanted:
        string = string.replace(char, "")
    list = string.split(",")
    return set(list)

s1 = "{'XXX-YYY'}"
s2 = "{'XXX-YYY', 'XXX-YYY', 'XXX-YYY', 'XXX-YYY'}"

s1_set = string2set(s1)
s2_set = string2set(s2)

s1_set = {'XXX-YYY'}

s2_set = {'XXX-YYY', ' XXX-YYY', ' XXX-YYY', ' XXX-YYY'}

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.