Mic*_*ael 0 python string list python-2.7
有没有办法从字符串:
"I like Python!!!"
Run Code Online (Sandbox Code Playgroud)
像这样的清单
['I', 'l', 'i', 'k', 'e', 'P', 'y', 't', 'h', 'o', 'n', '!', '!', '!']
Run Code Online (Sandbox Code Playgroud)
iCo*_*dez 13
使用列表理解:
>>> mystr = "I like Python!!!"
>>> [c for c in mystr if c != " "]
['I', 'l', 'i', 'k', 'e', 'P', 'y', 't', 'h', 'o', 'n', '!', '!', '!']
>>> [c for c in mystr if not c.isspace()] # alternately
['I', 'l', 'i', 'k', 'e', 'P', 'y', 't', 'h', 'o', 'n', '!', '!', '!']
>>>
Run Code Online (Sandbox Code Playgroud)
看起来你不想在结果列表中有任何空格,所以试试:
>>> s = "I like Python!!!"
>>> list(s.replace(' ',''))
['I', 'l', 'i', 'k', 'e', 'P', 'y', 't', 'h', 'o', 'n', '!', '!', '!']
Run Code Online (Sandbox Code Playgroud)
但你确定你需要一份清单吗?请记住,在大多数情况下,字符串可以像列表一样对待:它们是序列并且可以迭代,并且许多接受列表的函数也接受字符串.
>>> for c in ['a','b','c']:
... print c
...
a
b
c
>>> for c in 'abc':
... print c
...
a
b
c
Run Code Online (Sandbox Code Playgroud)