Reputation: 31
Given (in Python 2.7)..
myString='{hello,world}'
How do I go about converting the above into the set object {'hello', 'world'}
?
I tried eval(myString)
, but it throws NameError: name 'hello' is not defined
I tried ast.literal_eval(myString)
but it throws ValueError: malformed string
thanks!
Upvotes: 1
Views: 1842
Reputation: 29
Looks like you were close. If you put quotes around the individual elements, you can use Python's eval
>>> myString = "{'hello','world'}"
>>> eval(myString)
{'world', 'hello'}
Upvotes: 1
Reputation: 3172
In java you can do it this way:
First, if myString always starts with "{" and ends with "}", you get rid of those first by substring.
String myString = "{hello,world}"; String myStringFixed = myString.substring(1, myString.length() - 1);
The output of myStringFixed now would be "hello,world"
Convert the string into an array throught splitting.
String[] arrayOfStrings = myStringFixed.split(",");
The output of arrayOfStrings would be ["hello", "world"];
Now you can create a set via that array by running a loop and add those elements to the set.
Set stringSet = new HashSet();
for(int i = 0; i < arrayOfStrings.length; i++) { stringSet.add(arrayOfStrings[i]); }
Upvotes: 0