How to put string in a set as an individual item?

40k Views Asked by At

I have a string

sample = "http://www.stackoverflow.com"

I want convert this string to a set

final = {"http://www.stackoverflow.com"}

I tried the following code:

final = set(sample)

But i got the wrong out as

{u'.', u'/', u':', u'a', u'b', u'c', u'e', u'h', u'i', u'k', u'l', u'n', u'p', u's', u't', u'w'}

I also used

final  = ast.literal_eval(Sample)

and I got this

SyntaxError: invalid syntax

Is there any other solution for this

5

There are 5 best solutions below

0
On BEST ANSWER

Just do it:

In [1]: s = "http://www.stackoverflow.com"

In [2]: f = {s}

In [3]: type(f)
Out[3]: builtins.set

In [4]: f
Out[4]: {'http://www.stackoverflow.com'}
0
On

The set() class ,which is also considered a built-in type, accepts an iterable and returns the unique items from that iterable in a set object. Here since strings are considered a form of iterable --of characters-- you can't just call it on your string. Instead, you can either put the string object literally inside a set while defining it or if you're forced to use set() you can put it inside another iterable such as list or tuple before you pass it to set().

In [14]: s = {'sample string'}                                                                                                                                                                              

In [15]: s                                                                                                                                                                                                  
Out[15]: {'sample string'}

In [16]: s = set(['sample string'])                                                                                                                                                                         

In [17]: s                                                                                                                                                                                                  
Out[17]: {'sample string'}
0
On
sample = "http://www.stackoverflow.com"
final = set((sample, ))
0
On

you can do it with:

final = set(sample.split())

And if you had a string separated by spaces, it would leave you each word separated within the set.

example= "www.example.com www.natsoft.co www.google.com"

result = set(example.split())
print(result)

{'www.example.com', 'www.natsoft.co', 'www.google.com'}
0
On

The easiest way is final = {sample}.