Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print like printf in Python3?

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))
like image 581
Mike L Avatar asked Oct 04 '22 17:10

Mike L


People also ask

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

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.

What is %s %d %F in Python?

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.

How do I print %s in printf?

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 '%%'.

How do you print %s in Python?

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.


1 Answers

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}')
like image 246
Robᵩ Avatar answered Oct 19 '22 00:10

Robᵩ