Python 如何打印输入的内容?

Python 如何打印输入的内容?,python,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 y

我正在写一段代码,要求用户的名字,然后是第二个名字,然后是他们的年龄,但我打印出来,但我不知道如何请给出答案

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
使用


对于字符串,您可能需要考虑使用<代码> %s <代码> >代码> %d>代码> >;-(<)p> 您想使用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.")

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

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

这是固定代码:

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

这很容易理解,因为它只使用串联。

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

  • 老路

    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))
    
  • 新方式(首选方式)


新方法更加灵活,并提供了一些简洁的便利,比如给占位符一个索引。您可以在这里找到所有的差异和优势:

显示新的格式样式不是更好吗?事实上,我不喜欢它,旧的格式绝不会被弃用,OP的版本已经接近这一点了。但是,请随意使用新样式添加您自己的答案。(哦,太晚了,鲍德里克打败了你。)我必须承认,我一直在我的代码中编写
%
格式,这是我习惯的。不过,对于一个新手来说,最好学习当前被接受的样式。正如我所说,%-格式仍然是“被接受的”(我们几周前在这里讨论过,没有发现任何反对意见)。新的格式只是较新的Python版本提供的一种替代方法。在Python 3.6中:
print(f“那么,您是{firstName}{secondName},您是{age}岁。”
print("So, you're {} {} and you're {} years old.".format(firstName, secondName, age))