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

时间:2019-02-25 02:50:56

标签: python python-3.x string function

我不确定如何使此代码打印多个复数的输入。例如,如果输入“单名词,单名词,单名词”输入,它将打印为“单名词,单名词,复数名词”。由于某种原因,只有最后一个字符串变成复数。如何获得打印“复数名词,复数名词,复数名词”的字样?

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

2 个答案:

答案 0 :(得分:2)

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

您需要 tokenize 您的输入字符串。一种典型的方法是使用"dog"(和str.split()删除前导和尾随空格):

str.strip()

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

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

答案 1 :(得分:1)

使用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))
相关问题