How can I print like printf
in Python 3?
In Python 2, I used the following syntax:
print "a=%d,b=%d" % (f(x, n), g(x, n))
However, when I try to do this in Python 3, I get an error:
print("a=%d,b=%d") % (f(x, n), g(x, n))
What is the correct way to use printf python style formatting in Python 3?
Hello @MiroslavRalevic
I hope you are doing well, Here is the detailed Explaination!
In Python 3.6 and beyond, the most modern and recommended approach for string formatting is using f-strings (formatted string literals). They offer a clean and readable way to embed expressions directly inside string literals. This method makes the syntax much simpler and more intuitive, especially when you need to include variable values in strings. For example:
a = f(x, n)
b = g(x, n)
print(f"a={a}, b={b}")
Here, the f-string evaluates f(x, n)
and g(x, n)
within the string, so you don’t need to worry about calling str()
on the variables. It’s concise and easy to understand, and I highly recommend it if you’re using Python 3.6+.
Let me know if you have any Doubts!
That’s a great point! @ian-partridge To add on, before f-strings were introduced, the str.format()
method was the go-to for string formatting in Python. It still works well, especially for complex scenarios, and is supported across all Python 3 versions. Here’s an example:
a = f(x, n)
b = g(x, n)
print("a={}, b={}".format(a, b))
The str.format()
method is flexible because it allows you to control the order of arguments and format them as needed. It’s still a solid choice if you’re working with older versions of Python or need more customization.
Hey @MiroslavRalevic
Using % Operator (Old Style, Works in Python 3)
You can still use the % operator for formatting strings in Python 3, which closely resembles the old printf-style formatting from Python 2. However, this approach is less recommended in Python 3 compared to the newer methods like f-strings and str.format().
a = f(x, n)
b = g(x, n)
print(“a=%d,b=%d” % (a, b))
This method allows you to continue using the %-style formatting syntax that you used in Python 2, while still working correctly in Python 3. However, keep in mind that this approach is considered somewhat outdated.