简体   繁体   English

如何从用户输入的句子中打印列表?

[英]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'].所以我应该制作一个脚本,要求用户造一个句子,然后丢弃除小写以外的所有字符并打印像这样的小写字母 ['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:这是 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 = "," :您可能正在寻找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 :您的程序几乎可以,只是不打印每个小写字符append到一个列表,最后只打印该列表

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何要求用户提供布尔输入以限定if语句并使用Python中的该信息打印句子 - How to ask for a boolean input from a user to qualify if statements and print a sentence using that information in Python 如何打印从字典中提取信息的句子,其中包含列表 - How to print a sentence pulling information from a dictionary that has a list inside 根据用户输入从列表中打印值 - Print a value from a list based on user input 如何使用用户输入的单词创建句子 - how to create a sentence using words from user input 如何使用python通过句子打印用户输出 - How to print a user output by a sentence using python 如何打印用户从该列表中输入名称的完整列表? PYTHON - How do I print a full list where a user has input a name from that list? PYTHON 如何从带有特定项目的输入中打印列表 - How to print list from input with specific items 如何从用户输入中搜索单词列表的文本文件,并打印包含这些单词的行? - how can i search a text file of list of words from user input and print the line which contains these words? 如何从 python 中的列表中获取特定的多个值,如果用户输入等于多个值,则打印 output - How to get the specific multiple value out from a list in python and If the user input is equal to the mulitple values print output 根据词典列表中的用户输入,打印特定的键值 - Print particular key value based on the user input from list of dictionaries
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM