繁体   English   中英

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

[英]How to have multiple strings in one input to print in one line?

我不知道如何使这个代码打印多个输入所有复数。 例如,如果我输入“单名词,单名词,单名词”输入,它将打印为“单名词,单名词,复名词”。 由于某种原因,只有最后一个字符串变为复数。 怎样才能打印出“复数名词,复数名词,复数名词?”

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)))

使用str.split

def double(nouns):
    l = []
    for noun in nouns.split(', '):
        if noun.endswith("ey"):
            l.append(noun + "s")   
        elif noun.endswith("y"):
            l.append(noun[:-1] + "ies")
        elif noun.endswith("ch"): 
            l.append(noun + "es")
        else:
            l.append(noun + "s")
    return ', '.join(l)
noun = input("type in here")
print (plural(noun))

暂无
暂无

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

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