Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print formatted string in Python3?

Hey I have a question concerning this

print ("So, you're %r old, %r tall and %r heavy.") % (
    age, height, weight)

The line doesn't work in python 3.4 do anyone know how to fix this?

like image 466
Soxty Avatar asked Nov 11 '14 10:11

Soxty


People also ask

How do I format a string in Python 3?

Formatting string using format() method Format() method was introduced with Python3 for handling complex string formatting more efficiently. Formatters work by putting in one or more replacement fields and placeholders defined by a pair of curly braces { } into a string and calling the str. format().

How do you use %d and %f in Python?

The %d formatter is used to input decimal values, or whole numbers. If you provide a float value, it will convert it to a whole number, by truncating the values after the decimal point. The %f formatter is used to input float values, or numbers with values after the decimal place.

What does format () do in Python?

The format() method formats the specified value(s) and insert them inside the string's placeholder. The placeholder is defined using curly brackets: {}. Read more about the placeholders in the Placeholder section below. The format() method returns the formatted string.

What is %d in Python3?

The %d operator is used as a placeholder to specify integer values, decimals or numbers. It allows us to print numbers within strings or other values. The %d operator is put where the integer is to be specified. Floating-point numbers are converted automatically to decimal values. Python3.


2 Answers

Even though I don't know which exception you get, you can maybe try to use the format function instead:

print ("So, you're {0} old, {1} tall and {2} heavy.".format(age, height, weight))

And as mentioned within the other answers, you obviously had some issue with your parentheses.

I will still leave my solution as a reference if you want to use format.

like image 90
oopbase Avatar answered Oct 22 '22 01:10

oopbase


you write:

print("So, you're %r old, %r tall and %r heavy.") % (age, height, weight)

when the correct is:

print("So, you're %r old, %r tall and %r heavy." % (age, height, weight))

besides that, you should think about switching to the "new" .format style which is more pythonic and doesn't requice type declaration. Started with Python 3.0 but is backported to 2.6+

print("So, you're {} old, {} tall and {} heavy.".format(age, height, weight))
#or for pinning(to skip the variable expanding if you want something 
#specific to appear twice for example)
print("So, you're {0} old, {1} tall and {2} heavy and {1} tall again".format(age, height, weight))

or if you want only python 3.6+ formatting:

print(f"So, you're {age} old, {height} tall and {weight} heavy.")
like image 37
John Paraskevopoulos Avatar answered Oct 22 '22 01:10

John Paraskevopoulos