假设我有以下字符串:
sentence = 'Python is a programming language'
我怎样才能把它变成:
sentence_list = [P,y,t,h,o,n,i,s,a,p,r,o,g,r,a,m,m,i,n,g,l,a,n,g,u,a,g,e]
我写了下面的代码,但它并没有给我我想要的东西:
sentence = 'Python is a programming language'
for i in range(len(sentence)):
if sentence[i] == ' ':
sentence_new = sentence.replace('sentence[i]', '')
sentence_spaced = ' '.join(sentence_new)
sentence_list = sentence_spaced.split(' ')
print sentence_list
#OUTPUT: ['P', 'y', 't', 'h', 'o', 'n', '', '', 'i', 's', '', '', 'a', '', '', 'p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g', '', '', 'l', 'a', 'n', 'g', 'u', 'a', 'g', 'e']
答案 0 :(得分:4)
您可以使用list comprehension:
>>> sentence = 'Python is a programming language'
>>>
>>> [c for c in sentence if not c.isspace()]
['P', 'y', 't', 'h', 'o', 'n', 'i', 's', 'a', 'p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g', 'l', 'a', 'n', 'g', 'u', 'a', 'g', 'e']
答案 1 :(得分:2)
您只需list
和str.replace
(删除空格):
>>> sentence = 'Python is a programming language'
>>> list(sentence.replace(' ', ''))
['P', 'y', 't', 'h', 'o', 'n', 'i', 's', 'a', 'p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g', 'l', 'a', 'n', 'g', 'u', 'a', 'g', 'e']
>>>
如果您要删除不是字母的所有,可以使用filter
和str.isalpha
:
>>> sentence = 'ab1%^ &#$2cd'
>>> filter(str.isalpha, sentence)
['a', 'b', 'c', 'd']
>>>
答案 2 :(得分:0)
或使用replace
列出理解:
[s for s in sentence.replace(' ','')]