我如何将字符串转换为python中的集合
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27192455/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can i convert the string to a set in python
提问by crax
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
有没有其他解决方案
采纳答案by Kasramvd
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'}
回答by Kasramvd
set()class Return a new set or frozenset object whose elements are taken from iterable , and strings are iterable! you can put your string in a listor tuple. for refuse of fragmentation !
set()class 返回一个新的 set 或frozenset 对象,其元素取自 iterable ,字符串是iterable! 你可以把你的字符串放在 alist或tuple. 拒绝碎片化!
>>> set([sample])
set(['http://www.stackoverflow.com'])
>>> set((sample,))
set(['http://www.stackoverflow.com'])
回答by Michael Goerz
sample = "http://www.stackoverflow.com"
final = set((sample, ))
回答by iamanigeeit
The easiest way is final = {sample}.
最简单的方法是final = {sample}。

