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}')
Answer from Robแตฉ on Stack Overflow
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ tutorial โ€บ inputoutput.html
7. Input and Output โ€” Python 3.14.3 documentation
For example: >>> import math >>> print('The value of pi is approximately %5.3f.' % math.pi) The value of pi is approximately 3.142. More information can be found in the printf-style String Formatting section.
Discussions

How to use printf style formatting in Python 3? - TestMu AI Community
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? More on community.testmuai.com
๐ŸŒ community.testmuai.com
0
November 12, 2024
python - What is print(f"...") - Stack Overflow
I am reading through a python script that takes an input of XML files and outputs an XML file. However, I do not understand the printing syntax. Can someone please explain what f in print(f"..... More on stackoverflow.com
๐ŸŒ stackoverflow.com
language design - What are the differences between designing a print function Python-style as opposed to C-style? - Programming Language Design and Implementation Stack Exchange
What are the main differences between designing a print function similar to Python's print() as opposed to C's printf()? ... $\begingroup$ Not my downvotes, but they could be caused by the inappropriate use of "C++" when what is really meant is "C", and by using a non-equivalent Python example ... More on langdev.stackexchange.com
๐ŸŒ langdev.stackexchange.com
June 24, 2023
How to implement 'printf("%3d",1);' in python?
print("%3d"%1) Since presumably you will be using a variable, not a literal, you can use the newer, modern version of string formatting like this: var = 1 print(f"{var:>3}") More on reddit.com
๐ŸŒ r/learnpython
3
1
October 4, 2019
๐ŸŒ
Neuronsimulator
neuronsimulator.org โ€บ en โ€บ 8.0.2 โ€บ python โ€บ programming โ€บ io โ€บ printf.html
Printf (Formatted Output) โ€” NEURON documentation
Example: h.printf("\tpi=%-20.10g sin(pi)=%f\n", h.PI, h.sin(h.PI)) pi=3.141592654 sin(pi)=0.000000 42 ยท Pure Python equivalent example: import math print('\tpi=%-20.10g sin(pi)=%f' % (math.pi, math.sin(math.pi))) Note ยท The parentheses around the print argument are supplied in this way to ...
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_string_formatting.asp
Python String Formatting
Before Python 3.6 we used the format() method to format strings. The format() method can still be used, but f-strings are faster and the preferred way to format strings. The next examples in this page demonstrates how to format strings with the format() method.
๐ŸŒ
Quora
quora.com โ€บ What-is-the-printf-operator-in-Python
What is the printf operator in Python? - Quora
Answer (1 of 5): There is no printf in Python. There is print, which is a built-in function, but itโ€™s not an operator. If what youโ€™re asking is how can you get the printf functionality in Python, that we can do. printf, which first appeared in the C programming language 50 years ago, allows you...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-output-formatting
Python - Output Formatting - GeeksforGeeks
The format() method was introduced in Python 2.6 to enhance string formatting capabilities. This method allows for a more flexible way to handle string interpolation by using curly braces {} as placeholders for substituting values into a string. It supports both positional and named arguments, making it versatile for various formatting needs. For Example -
Published ย  July 11, 2025
๐ŸŒ
Yale
neuron.yale.edu โ€บ neuron โ€บ static โ€บ py_doc โ€บ programming โ€บ io โ€บ printf.html
Printf (Formatted Output) โ€” NEURON 7.7 documentation
Example: h.printf("\tpi=%-20.10g sin(pi)=%f\n", h.PI, h.sin(h.PI)) pi=3.141592654 sin(pi)=0.000000 42 ยท Pure Python equivalent example: import math print('\tpi=%-20.10g sin(pi)=%f' % (math.pi, math.sin(math.pi))) Note ยท The parentheses around the print argument are supplied in this way to ...
Find elsewhere
๐ŸŒ
TestMu AI Community
community.testmuai.com โ€บ ask a question
How to use printf style formatting in Python 3? - TestMu AI Community
November 12, 2024 - 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โ€ฆ
๐ŸŒ
Narkive
tutor.python.narkive.com โ€บ i2Ugd1vk โ€บ here-s-a-printf-function
[Tutor] here's a printf() function
But it can be a dangerous habit to try to equate Python and C too closely.) However your general point is correct. is checks for dentical objects, equality checks for identical values. So: If (A is B) is true then (A == B) is true also If (A == B) is true then (A is B) is still unknown Alan G. ... Please answer the following about the "printf()" function in C--"int printf( const char *format, ...
๐ŸŒ
PyFormat
pyformat.info
PyFormat: Using % and .format() for great good!
Python has had awesome string formatters for many years but the documentation on them is far too theoretic and technical. With this site we try to show you the most common use-cases covered by the old and new style string formatting API with practical examples.
๐ŸŒ
Real Python
realpython.com โ€บ python-string-formatting
Python String Formatting: Available Tools and Their Features โ€“ Real Python
December 2, 2024 - The different types of string formatting in Python include f-strings for embedding expressions inside string literals, the .format() method for creating string templates and filling them with values, and the modulo operator (%), an older method used in legacy code similar to Cโ€™s printf() function.
๐ŸŒ
Python Course
python-course.eu โ€บ python-tutorial โ€บ formatted-output.php
22. Formatted Output | Python Tutorial | python-course.eu
November 8, 2023 - To answer "Python has a print function and no printf function" is only one side of the coin or half of the truth. One can go as far as to say that this answer is not true. So there is a "printf" in Python? No, but the functionality of the "ancient" printf is contained in Python.
Top answer
1 of 7
150

The f means Formatted string literals and it's new in Python 3.6.


A formatted string literal or f-string is a string literal that is prefixed with f or F. These strings may contain replacement fields, which are expressions delimited by curly braces {}. While other string literals always have a constant value, formatted strings are really expressions evaluated at run time.


Some examples of formatted string literals:

>>> name = "Fred"
>>> f"He said his name is {name}."
"He said his name is Fred."

>>> name = "Fred"
>>> f"He said his name is {name!r}."
"He said his name is Fred."

>>> f"He said his name is {repr(name)}." # repr() is equivalent to !r
"He said his name is Fred."

>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal("12.34567")
>>> f"result: {value:{width}.{precision}}" # nested fields
result: 12.35

>>> today = datetime(year=2023, month=1, day=27)
>>> f"{today:%B %d, %Y}" # using date format specifier
January 27, 2023

>>> number = 1024
>>> f"{number:#0x}" # using integer format specifier
0x400
2 of 7
63

In Python 3.6, the f-string, formatted string literal, was introduced(PEP 498). In short, it is a way to format your string that is more readable and fast.

Example:

agent_name = 'James Bond'
kill_count = 9


# old ways
print("%s has killed %d enemies" % (agent_name,kill_count))

print('{} has killed {} enemies'.format(agent_name,kill_count))
print('{name} has killed {kill} enemies'.format(name=agent_name,kill=kill_count))
    

# f-strings way
print(f'{agent_name} has killed {kill_count} enemies')

The f or F in front of strings tell Python to look at the values , expressions or instance inside {} and substitute them with the variables values or results if exists. The best thing about f-formatting is that you can do cool stuff in {}, e.g. {kill_count * 100}.

You can use it to debug using print e.g.

print(f'the {agent_name=}.')
# the agent_name='James Bond'

Formatting, such as zero-padding, float and percentage rounding is made easier:

print(f'{agent_name} shoot with {9/11 : .2f} or {9/11: .1%} accuracy')
# James Bond shoot with  0.82 or  81.8% accuracy 

Even cooler is the ability to nest and format. Example date


from datetime import datetime

lookup = {
    '1': 'st',
    '21': 'st',
    '31': 'st',
    '2': 'nd',
    '22': 'nd',
    '3': 'rd',
    '23': 'rd'
}

dato = datetime.now()

print(f"{dato: %B %-d{lookup.get(f'{dato:%-d}', 'th')} %Y}")

# April 23rd 2022

Pretty formatting is also easier

tax = 1234

print(f'{tax:,}') # separate 1k \w comma
# 1,234

print(f'{tax:,.2f}') # all two decimals 
# 1,234.00

print(f'{tax:~>8}') # pad left with ~ to fill eight characters or < other direction
# ~~~~1234

print(f'{tax:~^20}') # centre and pad
# ~~~~~~~~1234~~~~~~~~

The __format__ allows you to funk with this feature. Example


class Money:
    
    def __init__(self, value, currency='โ‚ฌ'):
        self.currency = currency
        self.value = value
        
    def __repr__(self):
        return f'Money(value={self.value}, currency={self.currency})'
        
    def __format__(self, *_):
        
        return f"{self.currency}{float(self.value):.2f}"
        
        
tax = 12.3446
money = Money(tax, currency='$')

print(f'{money}')
# $12.34

print(money)
# Money(value=12.3446, currency=$)

There is much more. Readings:

  • PEP 498 Literal String Interpolation
  • Python String Formatting
๐ŸŒ
Medium
medium.com โ€บ @venu_madhav โ€บ master-the-python-output-formatting-4eb0c625ea47
Python variables | python print funtion | python loops | python control statements | python class | ML with python | lists | python output | Medium
December 16, 2024 - # Example 3 pi = 3.14159265359 print("Value of pi: 0.2f" % pi) #output Value of pi: 0000003.14 ยท The format specifier 0.2f used in the string "Value of pi: 0.2f" % pi does the following: ... The format() method was added in Python(2.6). ...
๐ŸŒ
Javatpoint
javatpoint.com โ€บ python-output-formatting
Python Output Formatting - Javatpoint
July 11, 2025 - Python Output Formatting with tutorial, tkinter, button, overview, canvas, frame, environment set-up, first python program, etc.
Top answer
1 of 3
9

It's mainly related to the basics of the type system, but sometimes related to other considerations on the philosophy of the language.

print with arbitrary values

Some languages have a print function that accepts arbitrary values. Others need the program to explicitly convert data to a string. What makes the difference is whether the language makes it possible to infer how to convert the data with some default conversion mechanism (e.g. integers printed in decimal, lists printed as something like the language's list constructor syntax, etc.).

In a dynamically typed language like Python, it's easy. All values have runtime type information, so the printing function can use that to determine how to print the argument.

In statically typed languages, there typically isn't enough information at runtime to find a sensible way to convert a value's representation to a string. For example, a word in memory could contain an integer or a float or a pointer and there's no way to find out which. So any automatic conversion to string has to follow some rules at compile time, where the compiler generates the correct formatting function based on the argument's static type.

C has no such mechanism. C is a low-level language which gives the programmer a lot of control. If you want to print an integer, you have to specify whether you want it in decimal, hexadecimal or octal. If you want to print a floating-point value, you have to specify how many digits of precision. This philosophy is prevalent in C, so the design of the language doesn't include any mechanism for selecting between different implementations of a function based on the argument type. (From C11 onwards there is such a mechanism, but it's restricted to selecting between floating point types for a few built-in functions.)

Many statically typed languages have an overloading mechanism that allows the selection of different implementations of a function based on the argument's type. For example, in C++, the << operator selects between different printing functions based on the type of its right-hand argument, so you can write cout << 1, cout << 1.5, cout << "hello", etc. (And << even selects between being a printing function and a bitwise operator, based on the type of its left-hand argument.) This is a compile-time mechanism: the compiler knows that there are many << functions, each with their type. In Haskell, this is the Show type class, with an instance for each type or type constructor for which a printing mechanism exists.

printf with a template

Almost all general-purpose languages have function that's similar to C's sprintf, often with a similar template syntax. They may or may not have a function that's similar to printf, combining the string templating with printing: when combining a string-printing function with a template formatting function is simple enough, there's no need for a function that does both.

For example, in Python, the equivalent of C's sprintf is the % operator, which uses a printf-like template syntax. This templating mechanism from the original version of the language is somewhat deprecated in modern Python in favor of a different template syntax that is accessible via the format method on the template string; the syntax is different, but the core principle is the same. Python only has a sprintf equivalent, not a printf equivalent, because there wouldn't be much point: it's almost as easy to write print(template % (arg1, arg2)) or print(template.format(arg1, arg2)) as it would be to write print(template, arg1, arg2).

Having separate functions requires constructing the resulting string in memory. In C, that's a big deal: you have to allocate enough memory, and C gives you a choice of allocators: you can use a global buffer, or a buffer on the stack, or a buffer allocated by malloc, or a buffer allocated by some custom allocator. So it's convenient to have a function that can directly print out the data piece by piece. In a high-level language like Python, the allocation is done entirely under the hood and allocating a string in memory is not considered a big deal.

The main reason some general-purpose don't have a printf or sprintf-like function is that it's hard to fit into a static type system. You have to match the content of the template string with the types of the other arguments, and even with the number of other arguments. In C, that's not a problem because the type system is very far from sound. It's the responsibility of the programmer to pass the correct number of arguments with the correct types. In dynamically typed languages, that's not a problem because the templating function can check argument types at runtime.

Many statically typed languages arrange some printf-like mechanism anyway, with various degree of โ€œcompiler magicโ€, i.e. you couldn't implement printf as a library function. For example, Pascal has special handling for some functions like write which accept multiple argument types and even a field width formatting syntax. You can write write('x=', x:3) but you can't make your own function that accepts a variable number of arguments, or that takes the extra width annotation :3. In Ocaml, the printf mechanism requires the template to be a string literal, which the compiler parses to deduce the expected type of the argument list: printf itself has a special type for which you can't build values normally, but sprintf "x=%3" has the type int -> string.

Haskell's type classes (a very fancy overloading mechanism) are powerful enough to define a printf function in the base library, but it requires runtime validation of the template against its type. The types of the arguments determine the type class of the template, which determines the implementation of the template-to-string conversion. The template-to-string conversion uses the template string to determine exactly what must be printed, but needs to validate that it matches the expected types for the arguments. For example, printf template 1 results in code that knows that it needs to format one integer, and will accept x=%3d as a template but not x=%s or x=%3d, y=%3d.

2 of 3
6

There is a price you need to pay for print to look like it does in python. Ask yourself if it is an acceptable price that fits well into your balance of goals and compromises.

The price is one of the following:

  • Dynamic type system with a runtime dispatch. With all the consequences - boxed values all over, limited static analysis availability, runtime overhead.
  • Function/method overloading (like in C++) - you no longer know what is the exact type of function arguments by looking at it. With an IDE with type hints you would not care, but not all languages have IDE integration ready, especially true for the small DSLs / amateur or toy languages. Also, presence of overloading may mess up badly with certain type systems (HM can handle it, but also at some extra cost).
  • Typed macro metaprogramming (e.g., as in Rust) - in my book, by far the preferable choice, but there is a lot of people with irrational fear of macros, and you're going to alienate them if you bake macros into such a core functionality of your standard library.
๐ŸŒ
Flexiple
flexiple.com โ€บ python โ€บ python-output-formatting
Python Output Formatting - Flexiple
March 19, 2024 - Formatting output using the string modulo operator (%) in Python allows for a type-specific formatting of strings. This method, often referred to as printf-style string formatting, involves using the % operator to embed variables into a string by placing them in a special format specifier, which includes the type of the data. ... The %s in this example, is used for string variables, and %d for integers.
๐ŸŒ
Diveintosystems
diveintosystems.org โ€บ book โ€บ C1-C_intro โ€บ input_output.html
1.2. Input/Output (printf and scanf)
Table 2 displays example programs for reading user input values in Python and C: When run, both programs read in two values (here, 30 and 67): ... Like printf, scanf takes a format string that specifies the number and types of values to read in (for example, "%d" specifies one int value).