Using %r with input() in python 3

2019-09-01 06:32发布

问题:

I'm new to python and having a bit of trouble. If you guys could help explain how to do this and why it works the way it does would be awesome. I'm doing the learn python the hard way lesson 11 in python 3 trying to make the change over. I've looked for the last hour or so trying to figure this out. I have tried all kinds of (), " ", ' ' combo's. Thanks for the help. I'm struggling with the step over to python 3 from codecademy python tutorials I've done. Here is what I originally wrote be for i messed with it.

I have tried putting it outside the () and in there own () but I keep reading errors.

print ("How old are you?"),
age = input("Enter: ")
print ("How tall are you?"),
height = input("Enter:")
print ("What are you in to?"),
interest = input("Enter: ")

print ("So your %r and %r tall. Cool what do you like?"),
print ("I like  to do %r "),

This code is running fine but the %r is not replacing with the user input().

回答1:

You need to mention which variables you want to substitute:

print("So your %r and %r tall. Cool what do you like?" % (age, height))

The string %r is not special in any way: it is just a placeholder value that is recognized by the formatting operator %.

Note: the trailing comma does not accomplish anything in Python 3 because print is just a regular function. If you want to suppress the newline, use the following instead:

print(..., end="")

In general, when reading Python documentation, guides, and tutorials, it's a good idea to check what version it targets. Python 2 and 3 have some significant differences.



回答2:

You can also try:

print("So your {} and {} tall. Cool what do you like?".format(age,height))


回答3:

try like this

print("So your",age, "and", height, "tall. Cool what do you like?")