如何在输入提示中添加字符串

时间:2014-12-09 00:09:22

标签: python string input

for eachemployee in Employeelist:
    name = str(input("Could you tell me what is your name:  "))
    print ("Hello!"+name)
    income = int(input("May I ask your monthly income:  "))

我想让输入提示在询问收入时说出人名,例如:

如果我在hui时输入"Could you tell me what is your name: ",我想要问下一个问题"May I ask hui's monthly income: "

我该怎么做?

3 个答案:

答案 0 :(得分:1)

修改

实际上,最好这样做:

income = int(input("May I ask {}{} monthly income:  "
                   .format(name, "'" if name.endswith('s') else "'s")))

通过使用conditional expressionstr.endswith,我们确保不会在已经以's结尾的名称末尾意外添加s


您只需将名称插入带有str.format的提示字符串:

income = int(input("May I ask {}'s monthly income:  ".format(name)))

此外,由于str(input(...))始终返回字符串对象,因此没有理由input

最后,您应该使用,print代替+

print("Hello!", name)

否则,输出将是Hello!hui,这是不可读的。

答案 1 :(得分:1)

for eachemployee in Employeelist:
    name = input("Could you tell me what is your name:  ") # str unnecessary 
    print ("Hello! " + name)
    income = int(input("May I ask {0}'s monthly income:".format(name)))

答案 2 :(得分:0)

替代方式:

income = int(input("May I ask " + name + "'s your monthly income:  "))