This article provides an overview of the print() function in Python, which is used to display strings, numbers, and variable values on the standard output ( sys.stdout ).
If you want to output to a file, refer to the following article:
print is a function in Python 3, but a statement in Python 2.
print xxx # Python 2 print(xxx) # Python 3
Executing Python 2 code containing the print statement in Python 3 will result in a SyntaxError. Parentheses () are required.
# print 'this is a pen' # SyntaxError: Missing parentheses in call to 'print'. Did you mean print('this is a pen')? print('this is a pen') # this is a pen
Be careful not to unintentionally run Python 2 instead of Python 3. To confirm the Python version you're using, consult this article:
This article focuses on the Python 3 print() function.
You can display strings or numbers by passing them as arguments to the print() function.
print('this is a pen') # this is a pen print(100) # 100
For lists or dictionaries, the entire contents are displayed. An example of displaying list elements separated by specific characters will be explained later.
print([0, 1, 2]) # [0, 1, 2] print('a': 0, 'b': 1, 'c': 2>) #
Strings are printed directly, while other types are printed using their __str__() methods. For example, when passing 1.00000 as the string '1.00000' , it prints as is. However, when passing it as the floating-point number 1.00000 , it prints as 1.0 .
print('1.00000') # 1.00000 print(1.00000) # 1.0
To display float types with a certain number of decimal places or apply other formats, use the format() method or f-strings. More on this later.
Use the textwrap and pprint modules to display long strings, lists, dictionaries, and more with wrapping and truncating.
In previous examples, string or number values are passed directly to the print() function. You can achieve the same output using variables containing these values.
To display elements of lists or dictionaries, specify indexes or keys.
s = 'this is a pen' print(s) # this is a pen l = [0, 1, 2] print(l) # [0, 1, 2] print(l[0]) # 0 d = 'a': 0, 'b': 1, 'c': 2> print(d) # print(d['b']) # 1 f = 1.00000 print(f) # 1.0
By default, print() appends a newline after the output.
print('abc') print('xyz') # abc # xyz
By providing a string as the end argument, it replaces the newline. For example, to concatenate outputs of consecutive print() functions without a newline, use an empty string '' .
print('abc', end='---') print('xyz') # abc---xyz print('abc', end='') print('xyz') # abcxyz
The default value of the end argument is the newline character '\n' .
When providing multiple variables, strings, or numbers as comma-separated arguments tp the print() function, they are displayed with whitespace as the default separator.
i = 100 print('apple', i, 0.123) # apple 100 0.123
By specifying the sep argument, you can change the separator from the default (whitespace) to any string. If you specify the newline character \n , the values will be displayed with a newline for each.
print('apple', i, 0.123, sep='----') # apple----100----0.123 print('apple', i, 0.123, sep='\n') # apple # 100 # 0.123
For more details on string line breaks, refer to the following article:
Also, if you want to concatenate multiple strings to create a new string, refer to the following article:
As mentioned above, when you directly print a list using print() , it looks like this:
l = [0, 1, 2] print(l) # [0, 1, 2]
By adding an asterisk * to the list and providing it as a function argument, each element is expanded and passed as a separate argument.
By default, each element is displayed separated by a space.
print(*l) # => print(0, 1, 2) # 0 1 2
You can specify the delimiter with the sep argument.
print(*l, sep='') # 012 print(*l, sep='-') # 0-1-2
Alternatively, you can create a concatenated string of the list elements and print it using print() .
s = '-'.join([str(i) for i in l]) print(s) # 0-1-2
There are three ways to embed the value of a variable into a string:
The official documentation on the printf style contains the following note:
Note: The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer formatted string literals, the str.format() interface, or template strings may help avoid these errors. Built-in Types - printf-style String Formatting — Python 3.11.3 documentation
Unless you're familiar with the C-style printf , which uses conversion specifiers like %d , %f.2 , and %s , it's recommended to use the format() method or f-strings, as mentioned in the official documentation.
Note that f-strings were added in Python 3.6 and are not available in earlier versions.
To replace %d , %s , etc., with variables, use the following syntax:
string % variable
If there are multiple variables, specify them as a tuple by enclosing them with () and separating them with commas , .
s = 'Alice' i = 25 print('Alice is %d years old' % i) # Alice is 25 years old print('%s is %d years old' % (s, i)) # Alice is 25 years old
Conversion specifiers are %d for integers, %f for floating-point numbers, and %s for strings. For more details on formatting options, see the official documentation below.
You can use the string method format() to replace the replacement fields <> in the string with the specified variables. If there are multiple variables, separate them with commas , .
string.format(variable)
print('Alice is <> years old'.format(i)) # Alice is 25 years old print('<> is <> years old'.format(s, i)) # Alice is 25 years old
By specifying an index (an integer starting from 0 ) in the replacement field <> , the value is replaced according to the position of the argument. This approach is helpful when you need to reuse the same value multiple times.
print(' is years old / '.format(s, i)) # Alice is 25 years old / AliceAliceAlice
By specifying a string in the replacement field <> , the value is replaced with the value specified as a keyword argument.
print(' is years old'.format(name=s, age=i)) # Alice is 25 years old
If you want to output the curly braces < , >in the string as they are, use > .
print('<> is <> years old / >'.format(s, i)) # Alice is 25 years old /
For more details on the format() method, see the article below.
F-strings are strings with an f before the string literal (e.g., f'xxx' ).
You can directly specify variables in the replacement field <> within the string.
s = 'Alice' i = 25 print(f's> is i> years old') # Alice is 25 years old
For more details on f-strings, see the following article.
By specifying a format string in the replacement field <> within the string calling the format() method or in an f-string, you can format and output numeric values in any desired format.
Write the format string as by placing the format string after the : . If you want to specify an index or name in the replacement field, write :format_string after it.
number = 0.45 print(' is '.format(number)) # 0.4500 is 45.00% print(f'number:.4f> is number:.2%>') # 0.4500 is 45.00%
Various output formats can be achieved using the format string:
i = 255 print('left : '.format(i)) print('center : '.format(i)) print('right : 8>'.format(i)) print('zero : '.format(i)) print('bin : '.format(i)) print('oct : '.format(i)) print('hex : '.format(i)) # left : 255 # center : 255 # right : 255 # zero : 00000255 # bin : 11111111 # oct : 377 # hex : ff f = 0.1234 print('digit : '.format(f)) print('digit : '.format(f)) print('exp : '.format(f)) print('percent : '.format(f)) # digit : 0.12 # digit : 0.123400 # exp : 1.2340e-01 # percent : 12%
Although the examples use the format() method, you can also apply the same format strings with f-strings.
For more detailed explanation of the format() method and format strings, refer to the article below.