Reputation:
Suppose I have the following string:
sentence = 'Python is a programming language'
How can I turn it into:
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]
I wrote the following code but it doesn't give me what I want:
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']
Upvotes: 0
Views: 216
Reputation:
All you need is list
and str.replace
(to remove spaces):
>>> 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']
>>>
If you want to remove everything that is not a letter, you can use filter
and str.isalpha
:
>>> sentence = 'ab1%^ &#$2cd'
>>> filter(str.isalpha, sentence)
['a', 'b', 'c', 'd']
>>>
Upvotes: 2
Reputation: 3453
Or list comprehension with replace
:
[s for s in sentence.replace(' ','')]
Upvotes: 0
Reputation: 129497
You can use a 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']
Upvotes: 4