In Python 2 I used:
print "a=%d,b=%d" % (f(x,n),g(x,n))
I've tried:
print("a=%d,b=%d") % (f(x,n),g(x,n))
Both %s and %d operatorsUses decimal conversion via int() before formatting. %s can accept numeric values also and it automatically does the type conversion. In case a string is specified for %d operator a type error is returned.
Answer. In Python, string formatters are essentially placeholders that let us pass in different values into some formatted string. 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.
Generally, printf() function is used to print the text along with the values. If you want to print % as a string or text, you will have to use '%%'.
What is % string formatting in Python? One of the older ways to format strings in Python was to use the % operator. You can create strings and use %s inside that string which acts like a placeholder. Then you can write % followed be the actual string value you want to use.
In Python2, print
was a keyword which introduced a statement:
print "Hi"
In Python3, print
is a function which may be invoked:
print ("Hi")
In both versions, %
is an operator which requires a string on the left-hand side and a value or a tuple of values or a mapping object (like dict
) on the right-hand side.
So, your line ought to look like this:
print("a=%d,b=%d" % (f(x,n),g(x,n)))
Also, the recommendation for Python3 and newer is to use {}
-style formatting instead of %
-style formatting:
print('a={:d}, b={:d}'.format(f(x,n),g(x,n)))
Python 3.6 introduces yet another string-formatting paradigm: f-strings.
print(f'a={f(x,n):d}, b={g(x,n):d}')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With