Advanced Input/Output and String Formatting in Python

Python offers powerful mechanisms to handle input/output operations and string formatting. Mastering these techniques will significantly enhance your ability to write efficient, readable, and elegant code. In this article, we’ll delve into advanced methods for input/output and modern string formatting approaches.

1. Advanced Input Methods

Reading Multiple Inputs

Python’s built-in input() function can be combined with methods like split() to read multiple inputs in a single line:

a, b, c = map(int, input("Enter three numbers: ").split())
print(f"You entered: {a}, {b}, {c}")

Example Input:

Output:

Reading Multiple Lines of Input

To read multiple lines until an EOF (End-of-File):

import sys

lines = sys.stdin.read().splitlines()
for line in lines:
    print(line)

This approach is helpful when input size is unknown beforehand.

2. Advanced Output Methods

Using print() with Custom Separators and Endings

The built-in print() function can use custom separators (sep) and endings (end):

print("apple", "banana", "cherry", sep=" | ", end=".\n")

Output:

Writing to Files using print()

You can direct output to files easily:

with open('output.txt', 'w') as file:
    print("Writing to a file", file=file)

Buffered vs Unbuffered Output

When handling large outputs or real-time logging, you might prefer unbuffered output:

import sys

print("Real-time log", flush=True)
sys.stdout.write("Another real-time log\n")
sys.stdout.flush()

3. String Formatting Techniques

Python provides three major ways to format strings:

%-formatting (Old-Style)

Though somewhat outdated, %-formatting is straightforward:

name = "Alice"
age = 30
print("My name is %s and I am %d years old." % (name, age))

str.format() Method

Introduced in Python 2.6, str.format() offers more flexibility:

name = "Bob"
height = 1.85
print("My name is {} and my height is {:.2f}m.".format(name, height))

You can also use positional and keyword arguments:

print("{1} loves {0}".format("coding", "Alice"))
print("{name} scored {score}".format(name="Charlie", score=95))

f-strings (Formatted String Literals)

Introduced in Python 3.6, f-strings are concise, powerful, and faster:

name = "Dana"
score = 92
print(f"{name} scored {score}% in her exams.")

You can embed expressions directly inside strings:

x, y = 10, 20
print(f"The sum of {x} and {y} is {x + y}.")

4. Formatting Specifications

Formatting specifications control alignment, width, precision, and more. The syntax is as follows:

{:[align][width][.precision][type]}
Examples:
  • Alignment:
print(f"{'left':<10}|{'right':>10}|{'center':^10}")

Output:

  • Precision (for floats):
pi = 3.1415926535
print(f"{pi:.2f}")  # 3.14

Output:

  • Padding with zeros:
number = 42
print(f"{number:05}")  # 00042

Output:

  • Thousands Separator:
large_number = 1234567890
print(f"{large_number:,}")  # 1,234,567,890

Output:

5. Practical Examples

Formatting a Table
data = [('Alice', 24), ('Bob', 30), ('Charlie', 22)]

print(f"{'Name':<10} | {'Age':>5}")
print("-" * 18)
for name, age in data:
    print(f"{name:<10} | {age:>5}")

Output:


Date and Time Formatting

Python datetime objects integrate seamlessly with formatting:

from datetime import datetime

now = datetime.now()
print(f"Current time: {now:%Y-%m-%d %H:%M:%S}")

Example Output:

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top