Use the input()
function, to take input from a user, and the print()
function, we display output on the screen.
Python Input Formatting
Read Jupyter Note
Python Output Formatting
Most of the time, we need to format output instead of merely printing space-separated values. For example, we want to display the string left-justified or in the center. We want to show the number in various formats.
You can display output in various styles and formats using the following functions.
str.format()
repr()
str.rjust()
str.ljust()
, andstr.center()
.str.zfill()
- The
%
operator can also use for output formatting
1. str.format()
Method
The str.format()
method allows you to insert variables into strings dynamically and control their presentation.
"string {}".format(value)
Key Features
- Use positional or keyword arguments to inject values.
- Control precision for numbers.
- Align text (left, right, center) within specified widths.
# Number formatting
print("Pi is approximately {:.2f}".format(3.14159))
# Output
Pi is approximately 3.14
# Alignment
print("{:<10} | {:^10} | {:>10}".format("Left", "Center", "Right"))
Left | Center | Right
- Format Output String by its positions
# Positional arguments
print("Hello, {}!".format("Alice"))
# Output
Hello, Alice!
Another Example
firstName = input("Enter First Name ")
lastName = input("Enter Last Name ")
organization = input("Enter Organization Name ")
print("\n")
print('{0}, {1} works at {2}'.format(firstName, lastName, organization))
print('{1}, {0} works at {2}'.format(firstName, lastName, organization))
print('FirstName {0}, LastName {1} works at {2}'.format(firstName, lastName, organization))
print('{0}, {1} {0}, {1} works at {2}'.format(firstName, lastName, organization))
Teslim, Adeyanju works at Apple Ltd
Adeyanju, Teslim works at Apple Ltd
FirstName Teslim, LastName Adeyanju works at Apple Ltd
Teslim, Adeyanju Teslim, Adeyanju works at Apple Ltd
- Accessing Output String Arguments by name
# Keyword arguments
print("{name} is {age} years old.".format(name="Alice", age=25))
# output
Alice is 25 years old.
name = input("Enter Name ")
marks = input("Enter marks ")
print("\n")
print('Student: Name: {firstName}, Marks: {percentage}%'.format(firstName=name, percentage=marks))
Enter Name Jhon
Enter marks 74
Student: Name: Jhon, Marks: 74%
- Output Alignment by Specifying a Width
text = input("Enter text ")
print("\n")
# left aligned
print('{:<25}'.format(text)) # Right aligned print('{:>25}'.format(text))
# centered
print('{:^25}'.format(text))
Enter text This is a sample text
This is a sample text
This is a sample text
This is a sample text
- Specifying a Sign While Displaying Output Numbers
positive_number = float(input("Enter Positive Number "))
negative_number = float(input("Enter Negative Number "))
print("\n")
# sign '+' is for both positive and negative number
print('{:+f}; {:+f}'.format(positive_number, negative_number))
# sign '-' is only for negative number
print('{:f}; {:-f}'.format(positive_number, negative_number))
Enter Positive Number 25.25
Enter Negative Number -15.50
+25.250000; -15.500000
25.250000; -15.500000
- Display Output Number in Various Format
number = int(input("Enter number "))
print("\n")
# 'd' is for integer number formatting
print("The number is:{:d}".format(number))
# 'o' is for octal number formatting, binary and hexadecimal format
print('Output number in octal format : {0:o}'.format(number))
# 'b' is for binary number formatting
print('Output number in binary format: {0:b}'.format(number))
# 'x' is for hexadecimal format
print('Output number in hexadecimal format: {0:x}'.format(number))
# 'X' is for hexadecimal format
print('Output number in HEXADECIMAL: {0:X}'.format(number))
Enter number 356
The number is:356
Output number in octal format : 544
Output number in binary format: 101100100
Output number in hexadecimal format: 164
Output number in HEXADECIMAL: 164
- Display Numbers as a float type
number = float(input("Enter float Number "))
print("\n")
# 'f' is for float number arguments
print("Output Number in The float type :{:f}".format(number))
# padding for float numbers
print('padding for output float number{:5.2f}'.format(number))
# 'e' is for Exponent notation
print('Output Exponent notation{:e}'.format(number))
# 'E' is for Exponent notation in UPPER CASE
print('Output Exponent notation{:E}'.format(number))
Enter float Number 234.567
Output Number in The float type :234.567000
padding for output float number234.57
Output Exponent notation2.345670e+02
Output Exponent notation2.345670E+02
2. repr()
Function
The repr()
function generates a string representation of an object that can be used to recreate the object in Python.
Key Use Case
- Often used for debugging.
- Represents special characters and raw strings explicitly.
Example
x = "Hello\nWorld"
print(str(x)) # Hello
# World
print(repr(x)) # 'Hello\nWorld'
3. Alignment with str.rjust()
, str.ljust()
, and str.center()
These methods allow you to align strings within a given width by padding them with spaces or custom characters.
Methods
str.ljust(width[, fillchar])
: Left-aligns the string.str.rjust(width[, fillchar])
: Right-aligns the string.str.center(width[, fillchar])
: Centers the string.
Examples
text = "Python"
# Left-align
print(text.ljust(10, '-')) # Output: Python----
# Right-align
print(text.rjust(10, '*')) # Output: ****Python
# Center
print(text.center(10, '=')) # Output: ==Python==
4. Zero-Padding with str.zfill()
The str.zfill()
method pads the numeric string on the left with zeros, ensuring the string has a specified width.
num = "42"
print(num.zfill(5)) # Output: 00042
5. Using the %
Operator for Formatting
This old-style string formatting uses placeholders like %s
(string), %d
(integer), and %f
(float).
"string with placeholders" % (values)
# Basic usage
name = "Alice"
age = 25
print("Name: %s, Age: %d" % (name, age))
# Formatting numbers
pi = 3.14159
print("Pi is approximately %.2f" % pi) # Output: Pi is approximately 3.14
6. f-Strings (Recommended for Python 3.6+)
f-Strings allow inline expressions and are the most modern and readable way to format strings.
f"string with {variable}
name = "Alice"
age = 25
pi = 3.14159
# Inline variables
print(f"Name: {name}, Age: {age}")
# Number formatting
print(f"Pi is approximately {pi:.2f}") # Output: Pi is approximately 3.14
# Alignment
print(f"{'Left':<10} | {'Center':^10} | {'Right':>10}")
7. Comparison of Methods
Method | Features | Use Case |
str.format() | Flexible, works with positional and keyword arguments, supports alignment and number formatting. | General-purpose, highly readable. |
repr() | Gives unambiguous string representations. | Debugging, raw string representation. |
str.ljust() | Simple alignment using padding characters. | Aligning text with fixed width. |
str.rjust() | Aligns text to the right with padding characters. | Right-aligned formatting. |
str.center() | Centers text within a specified width. | Centering content in tables. |
str.zfill() | Zero-pads strings to the left. | Formatting numbers with leading zeros. |
% operator | Legacy method, uses placeholders for formatting. | Quick formatting in legacy codebases. |
f-Strings | Concise, supports expressions, modern and efficient. | Best choice for Python 3.6 and later. |
Tips for Effective Output Formatting
- Use
f-strings
for readability and efficiency. - Use
str.format()
when positional or keyword arguments are beneficial. - For table-like output, use
str.ljust()
,str.rjust()
, andstr.center()
. - Use
repr()
for debugging andzfill()
for formatting numbers.