gpt4 book ai didi

python - 如何在一个输入中有多个字符串打印在一行中?

转载 作者:太空宇宙 更新时间:2023-11-03 15:35:53 24 4
gpt4 key购买 nike

我不确定如何让这段代码打印多个输入,全部为复数。例如,如果我输入“单名词、单名词、单名词”,它会打印出“单名词、单名词、复数名词”。出于某种原因,只有最后一个字符串变成复数。我怎样才能让它打印出“plural-noun, plural-noun, plural-noun?”

def double(noun):
if noun.endswith("ey"):
return noun + "s"
elif noun.endswith("y"):
return noun[:-1] + "ies"
elif noun.endswith("ch"):
return noun + "es"
else:
return noun + "s"
noun = input("type in here")
print (double(noun))

最佳答案

input() 将返回用户输入的整行。也就是说,如果用户键入 bird, cat, dog,您的 plural 函数将收到一个字符串 "bird, cat, dog" 而不是分别使用单独的 "bird""cat""dog" 字符串调用。

您需要标记您的输入字符串。执行此操作的典型方法是使用 str.split()(和 str.strip() 删除前导和尾随空格):

nouns = input("type in here").split(",")
for noun in nouns:
print(plural(noun.strip()))

或者,如果您希望所有结果都以逗号分隔并打印在一行中:

nouns = input("type in here").split(",")
print(", ".join((plural(noun.strip()) for noun in nouns)))

关于python - 如何在一个输入中有多个字符串打印在一行中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54858850/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com