简体   繁体   中英

How to print a list from user input sentence?

So I am supposed to make a script that asks user to make a sentence then discard all characters but lower case and print the lower case letters like this ['m', 'y', 'p', 'a', 's', 's', 'w', 'o', 'r', 'd'].

My script:

#!/usr/bin/python3

sentence = input("Enter a sentence: ")

for letter in sentence:
    if letter.islower():
        print(letter)

and this is the output:

 oeshisw r k

Seems like you want to produce a list, you have list comprehensions to make life easy:

l = ['P', 'm', 'y', 'H', 'p', 'a', 's', 's', 'w', 'o', 'r', 'd']

out = [i for i in l if i.islower()]
print(out)
# ['m', 'y', 'p', 'a', 's', 's', 'w', 'o', 'r', 'd']

Which is equivalent to:

out = []
for i in l:
    if i.islower():
        out.append(i)

print(out)
# ['m', 'y', 'p', 'a', 's', 's', 'w', 'o', 'r', 'd']

You might be looking for end = "," :

sentence = input("Enter a sentence: ")

for letter in sentence:
    if letter.islower():
        print(letter, end=",")
#                         ^^^

Your program is almost OK, only instead of printing every lowercase character, append it to a list, and finally print only that list :

sentence = input("Enter a sentence: ")

lowercases = []                    # prepare an empty list

for letter in sentence:
    if letter.islower():
        lowercases.append(letter)

print(lowercases)                  # print the filled list

Test:

Enter a sentence: The End of Universe.
['h', 'e', 'n', 'd', 'o', 'f', 'n', 'i', 'v', 'e', 'r', 's', 'e']

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