简体   繁体   中英

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.

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:

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 ;-)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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