简体   繁体   English

您如何打印输入的内容?

[英]How do you print out the input you put in?

I am writing a piece of code which asks for the users first name then second name and then their age but then i print it out but I'm not sure how to please give an answer. 我正在编写一段代码,询问用户的名字,名字,年龄,但是随后我将其打印出来,但是我不确定如何给出答案。

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

You want to use string.format. 您要使用string.format。

You use it like so: 您可以这样使用它:

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

Or in Python 3.6 upwards, you can use the following shorthand: 或者在Python 3.6以上版本中,您可以使用以下速记:

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

Use 采用

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

You might want to consider using %s for the strings and %d for the number, though ;-) 您可能要考虑将%s用作字符串,将%d用作数字,尽管;-)

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

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

This is the fixed code: 这是固定的代码:

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

It is pretty easy to understand, since this just uses concatenation. 这很容易理解,因为它仅使用串联。

There are two ways to format the output string: 有两种格式化输出字符串的方式:

  • Old way 旧方法

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

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

The new way is much more flexible and provides neat little conveniences like giving placeholders an index. 新方法更加灵活,并提供了一些小巧的便利,例如为占位符提供索引。 You can find all the differences and advantages here : PyFormat 您可以在这里找到所有的区别和优点: PyFormat

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM