Python Tutorial – Output
Contents
Python’s Output Formatting ✈️
Python there are various ways to display program output and input, such as printing on the computer screen or writing to a file or entering a command from the keyboard.
Example
num = 123
name = 'John'
print(num)
print(name)
Results
123
John
Detailed Explanation of Output Formatting
Python has three ways... 1. Formatted String Literals (f-strings). 2. str.format() method or manual string formatting. 3. % operator (old string formatting).
Example @ f-strings
"""
f-strings
"""
import math
pi = math.pi
print(type(pi))
print(f"PI = {pi:.3f}")
print(f'PI = {pi:.10f}')
print('PI = {pi:.10f}')
# '!a' applies asciiO,
# '!s' applies strO, and
# '!r' applies reprO
animals = 'cat'
print(type(animals))
print(f'My {animals}.')
print(f'My {animals!r}.')
print(f'My {animals!s}.')
print(f'My {animals!a}.')
name = {'John': 18, 'Jack': 20, 'Tony': 25}
print(type(name))
print('12345 ==> 12345')
for name, age in name.items():
# The integer after ':' can set the width
# of the field characters
print(f'{name:5} ==> {age:5d}')
Results
<class 'float'>
PI = 3.142
PI = 3.1415926536
PI = {pi:.10f}
<class 'str'>
My cat.
My 'cat'.
My cat.
My 'cat'.
<class 'dict'>
12345 ==> 12345
John ==> 18
Jack ==> 20
Tony ==> 25
Example @ str.format()
"""
str_format
"""
print("My {}'s name is {}!".format("cat", "Salud"))
print('{0} and {0}'.format('John', 'Jack'))
print('{0} and {1}'.format('John', 'Jack'))
print('{1} and {0}'.format('John', 'Jack'))
print('{1} and {1}'.format('John', 'Jack'))
print("The {cat}'s name is {name}."
.format(cat='cat', name='Salud'))
print('The cat of {0}, {1}, and {other}.'
.format('John', 'Jack', other='Tony'))
table = {'John': 12, 'Jack': 20, 'Tony': 30}
print('Jack: {0[Jack]:d}; Tony: {0[Tony]:d}; '
'John: {0[John]:d}'.format(table))
table = {'John': 12, 'Jack': 20, 'Tony': 30}
print('Tony: {Tony:d}; John: {John:d}; Jack: {Jack:d}'
.format(**table))
print('0123456789A')
for x in range(1, 5):
print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))
Results
My cat's name is Salud!
John and John
John and Jack
Jack and John
Jack and Jack
The cat's name is Salud.
The cat of John, Jack, and Tony.
Jack: 20; Tony: 30; John: 12
Tony: 30; John: 12; Jack: 20
0123456789A
1 1 1
2 4 8
3 9 27
4 16 64
Example @ manual string formatting
"""
manual_string_formatting
"""
print('0123456789A')
for x in range(1, 5):
print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')
# Note use of 'end' on previous line
print(repr(x*x*x).rjust(4))
print('1'.zfill(3))
print('1'.zfill(5))
print('1'.zfill(7))
print('-1'.zfill(7))
print('1.0'.zfill(5))
print('1.11'.zfill(5))
print('1.111'.zfill(5))
Results
0123456789A
1 1 1
2 4 8
3 9 27
4 16 64
001
00001
0000001
-000001
001.0
01.11
1.111
Example @ % operator ( old string formatting )
"""
old_string_formatting
"""
_id_ = 123
name = 'Tony'
age = 35
high = 175.5
weight = 65.3
# %s
print('My name is %s' % name)
# %d
print('My _id_ is %d' % _id_)
print('My age is %d' % age)
# %f
print('My high is %.3f' % high)
print('My weight is %.1f' % weight)
# 000123
print('My _id_ is %06d' % _id_)
# 123
print('My _id_ is %03d' % _id_)
# 123
print('My _id_ is %02d' % _id_)
# %s %d
print('My name is %s and I am %d years old.'
% (name, age))
print('My name is %s and I am %d years old.'
% (name, age+1))
# %d %s %f
print('ID : %d | Name : %s | Age : %d | High : '
'%.2f | Weight : %.2f'
% (_id_, name, age, high, weight))
# %s %s %s
print('ID : %s | Name : %s | Age : %s | High : '
'%s | Weight : %s'
% (_id_, name, age, high, weight))
Results
My name is Tony
My _id_ is 123
My age is 35
My high is 175.500
My weight is 65.3
My _id_ is 000123
My _id_ is 123
My _id_ is 123
My name is Tony and I am 35 years old.
My name is Tony and I am 36 years old.
ID : 123 | Name : Tony | Age : 35 | High : 175.50 | Weight : 65.30
ID : 123 | Name : Tony | Age : 35 | High : 175.5 | Weight : 65.3
Other Common Conversion Characters
\\ : Backslash (\). \' : Single quote ('). \" : Double quote ("). \n : ASCII Linefeed (LF). \r : ASCII Carriage Return (CR). \t : ASCII Horizontal Tab (TAB).
Example
"""
other_common_conversion_characters
"""
# '\n', like C language
print("Hello")
print("Hello\n")
print("Hello\r")
print("Hello\n\r")
print("Hello\'s")
print("Hello\\")
print("\"Hello\"")
print("Hello\t", end='')
print("Hello")
print("-----------------")
# When end=' ' is omitted, print() will default to end='\n'
# print("Hello") = print("Hello", end='\n')
print("Hello", end='\n')
print("Hello")
print("Hello", end='\t')
print("Hello")
print("-----------------", end='\r')
Results
Hello
Hello
Hello
Hello
Hello's
Hello\
"Hello"
Hello Hello
-----------------
Hello
Hello
Hello Hello
-----------------
Process finished with exit code 0