简体   繁体   中英

How to turn a sentence into a list containing its letters?

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']

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']

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']
>>>

或者用replace列出理解:

[s for s in sentence.replace(' ','')]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM