[英]How do you print out the input you put in?
我正在编写一段代码,询问用户的名字,名字,年龄,但是随后我将其打印出来,但是我不确定如何给出答案。
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
您要使用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.")
采用
print ("So, you're %r %r and you're %r years old." % (
firstName, secondName, age))
您可能要考虑将%s
用作字符串,将%d
用作数字,尽管;-)
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))
新方法更加灵活,并提供了一些小巧的便利,例如为占位符提供索引。 您可以在这里找到所有的区别和优点: PyFormat
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.