Output Formatting

In Python programming, the output can be formatted in various ways. See some coding examples below.

 

Example 1

The following example shows the addition of two floating-point numbers. After performing addition operation, the result has been formatted up to 2 decimal places using the format() method .

# Formatting output for floating-point addition
x = input("Enter value of a: ")
a = float(x)
y = input("Enter value of b: ")
b = float(y)
sum = a + b;
result = format(sum, '.2f') # formatting result up to 2 decimal places
print("\nSUM:", result)
print("\nSUM: %.2f" % sum) # alternative option using % operator (old style)

Output:

Enter value of a: 23.65258923

Enter value of b: 32.21237196

SUM: 55.86

SUM: 55.86

 

Example 2

The following example shows the basic formatting with format() method using default, positional and keyword arguments.

# Default arguments
print("Hi {}, your semester grade is {}.".format("Robin Smith", 8.92))

# Positional arguments
print("Hi {0}, your semester grade is {1}.".format("Robin Smith", 8.92))

# Keyword arguments
print("Hi {name}, your semester grade is {grade}.".format(name="Robin Smith", grade=8.92))

# Mixed arguments
print("Hi {0}, your semester grade is {grade}.".format("Robin Smith", grade=8.92))

Output:

Hi Robin Smith, your semester grade is 8.92.
Hi Robin Smith, your semester grade is 8.92.
Hi Robin Smith, your semester grade is 8.92.
Hi Robin Smith, your semester grade is 8.92.

 

Example 3

The following example shows the use of keyword arguments namely “sep=<str>” and “end=<str>” for output formatting.

# Using sep=<str> keyword argument
data = {'hello': 1, 'hi': 2, 'bye': 3}
print("Example of sep=<str>")
for k, v in data.items():
print(k, v, sep=' -> ')

# Using end=<str> keyword argument
print("\nExample of end=<str>")
for n in range(10):
print(n, end=(' ' if n < 9 else '\n'))

Output:

Example of sep=<str>
hello -> 1
hi -> 2
bye -> 3

Example of end=<str>
0 1 2 3 4 5 6 7 8 9