你如何打印输入的输入?

时间:2017-06-21 14:04:09

标签: python

我正在编写一段代码,询问用户的第一个名字,然后是第二个名字,然后是他们的年龄,然后我将其打印出来,但我不确定如何给出答案。

print ("What is your first name?"),
firstName = input()
print ("What is you last name?"),
secondName = input()
print ("How old are you?")
age = input()

print ("So,  you're %r  %r and you're %r years old."), firstName, secondName, age

5 个答案:

答案 0 :(得分:5)

您想使用string.format。

你这样使用它:

print ("So, you're {} {} and you're {} years old.".format(firstName, secondName, age))

或者在Python 3.6中,您可以使用以下简写:

print (f"So, you're {firstName} {secondName} and you're {age} years old.")

答案 1 :(得分:0)

使用

print ("So, you're %r  %r and you're %r years old." % (
    firstName, secondName, age))

您可能需要考虑使用%s作为字符串,%d作为数字; - )

答案 2 :(得分:0)

Python中的新样式字符串格式:

print("So, you're {} {} and you're {} years old.".format(firstName, secondName, age))

答案 3 :(得分:0)

这是固定代码:

firstName = input("What is your first name?")
secondName = input("What is you last name?")
age = input("How old are you?")

print ("So,  you're " + firstName + " " + secondName + " and you're " + age + " years old.")

这很容易理解,因为这只是使用连接。

答案 4 :(得分:0)

有两种格式化输出字符串的方法:

  • 旧方式

    print("So, you're %s %s and you're %d years old." % (firstName, secondName, age)
    
  • 新方式(首选方式)

    print("So, you're {} {} and you're {} years old.".format(firstName, secondName, age))
    

新方法更加灵活,并提供简单的便利,例如为占位符提供索引。您可以在此处找到所有差异和优势:PyFormat