Mastering Formatted Printing and Regular Expressions in Python: A Complete Guide

Formatted Printing in Python

Formatted printing in Python refers to the process of presenting text with a specific layout, aligning variables, and embedding values in a string in an easy-to-read manner. It helps in making the output more user-friendly, especially when handling complex data structures or printing information to a user or a report.

1. Basic Formatted Printing

In Python, the simplest way to perform formatted printing is by using the print() function. There are several ways to format strings, including using f-strings (formatted string literals), the str.format() method, and the % operator.

a. F-Strings (Python 3.6+)

Introduced in Python 3.6, f-strings are a powerful and concise way to format strings. The syntax involves prefixing the string with an ‘f’ or ‘F’ and embedding variables or expressions inside curly braces {}.

pythonCopyEditname = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")

Output:

csharpCopyEditMy name is Alice and I am 30 years old.

b. str.format() Method

Before f-strings, Python used the str.format() method for formatted string output. It allows you to insert placeholders using {} and fill them with arguments passed to format().

pythonCopyEditname = "Bob"
age = 25
print("My name is {} and I am {} years old.".format(name, age))

Output:

csharpCopyEditMy name is Bob and I am 25 years old.

c. % Operator

This is the old-style formatting, and while it’s still in use, it is considered less readable compared to f-strings and str.format().

pythonCopyEditname = "Charlie"
age = 28
print("My name is %s and I am %d years old." % (name, age))

Output:

csharpCopyEditMy name is Charlie and I am 28 years old.

2. Formatting Numbers

Formatted printing is especially useful when you need to display numbers in a specific format, such as rounding, padding, or aligning.

a. Padding with Spaces and Zeros

You can align text or numbers by specifying a width. This is useful when printing tables or lists of numbers.

pythonCopyEdit# Right-align numbers
print(f"{123:>10}")  # Right-align in a 10-character wide field

# Left-align numbers
print(f"{123:<10}")  # Left-align in a 10-character wide field

# Pad with zeros
print(f"{5:0>5}")  # Pad with zeros, making the length 5

Output:

markdownCopyEdit       123
123       
00005

b. Floating Point Formatting

When dealing with floating-point numbers, you can specify the number of decimal places to display.

pythonCopyEditpi = 3.14159265358979
print(f"{pi:.2f}")  # Round to 2 decimal places

Output:

CopyEdit3.14

3. Advanced Formatting with Alignment and Width

You can use :<, :>, and :^ to align text, and you can also set a specific width for the printed output. Here’s an example using multiple columns:

pythonCopyEditdata = [("Alice", 25, 5.6), ("Bob", 30, 5.8), ("Charlie", 28, 5.7)]
print(f"{'Name':<10}{'Age':<5}{'Height':<10}")
for name, age, height in data:
    print(f"{name:<10}{age:<5}{height:<10}")

Output:

cssCopyEditName       Age  Height   
Alice      25   5.6      
Bob        30   5.8      
Charlie    28   5.7      

Regular Expressions in Python

Regular expressions (regex) are a powerful tool for pattern matching and text manipulation. They allow you to search for specific patterns within a string and can be used for tasks like validation, searching, replacing, and splitting strings.

1. Basic Regular Expressions

Python provides the re module to work with regular expressions. The most common methods include search(), match(), findall(), sub(), and split().

a. re.search()

The re.search() function searches for the first match of a pattern in a string.

pythonCopyEditimport re

pattern = r"\d+"  # Match one or more digits
text = "I have 15 apples"
match = re.search(pattern, text)

if match:
    print("Found:", match.group())
else:
    print("No match found.")

Output:

makefileCopyEditFound: 15

b. re.findall()

The re.findall() function finds all non-overlapping matches of a pattern in a string.

pythonCopyEditimport re

pattern = r"\d+"  # Match one or more digits
text = "I have 15 apples and 20 oranges"
matches = re.findall(pattern, text)
print("Found:", matches)

Output:

arduinoCopyEditFound: ['15', '20']

c. re.sub()

The re.sub() function is used to replace all occurrences of a pattern with a new string.

pythonCopyEditimport re

pattern = r"\d+"  # Match digits
text = "I have 15 apples and 20 oranges"
new_text = re.sub(pattern, "X", text)
print(new_text)

Output:

cssCopyEditI have X apples and X oranges

2. Special Characters in Regular Expressions

In regular expressions, special characters have specific meanings. Some of the most commonly used ones include:

  • . (dot): Matches any character except a newline.
  • ^: Anchors the match at the beginning of the string.
  • $: Anchors the match at the end of the string.
  • \d: Matches any digit (0-9).
  • \D: Matches any non-digit character.
  • \w: Matches any word character (alphanumeric + underscore).
  • \W: Matches any non-word character.

Example: Matching an Email Address

pythonCopyEditimport re

pattern = r"[\w.-]+@[\w.-]+\.\w+"  # Basic email regex
text = "My email is [email protected]"
match = re.search(pattern, text)

if match:
    print("Found:", match.group())

Output:

graphqlCopyEditFound: [email protected]

3. Advanced Regular Expressions

You can use more complex patterns to match sequences of characters with specific conditions. Here’s an example of matching a phone number with a specific format (e.g., (123) 456-7890).

pythonCopyEditimport re

pattern = r"\(\d{3}\) \d{3}-\d{4}"  # Match phone number format
text = "My phone number is (123) 456-7890"
match = re.search(pattern, text)

if match:
    print("Found:", match.group())

Output:

makefileCopyEditFound: (123) 456-7890

Do’s and Don’ts of Regular Expressions

Do’s:

  1. Escape Special Characters: Always escape characters like . or * when you need them to be treated literally (e.g., \. to match a dot).
  2. Test Your Regex: Use online regex testers or Python scripts to test your expressions before applying them.
  3. Use Raw Strings: When working with regex in Python, always use raw string literals (prefix your regex with r) to avoid escaping backslashes.
  4. Be Specific with Patterns: Try to be as specific as possible to avoid unexpected matches. The more specific your regex, the more efficient it will be.

Don’ts:

  1. Don’t Overuse Regex: While regex is powerful, it’s not always the best tool for every string parsing task. Use built-in string methods when appropriate.
  2. Avoid Complex Patterns Without Comments: Complex regular expressions should be documented to avoid confusion and errors.

Exceptions in Formatted Printing and Regular Expressions

  • Formatted Printing: Ensure the variable data types are compatible with the format. For example, trying to format a string as an integer will raise a ValueError.
  • Regular Expressions: Always handle cases where no match is found. Functions like search() and match() return None when no match is found, and attempting to access group() on None will raise an AttributeError.

Conclusion

Formatted printing and regular expressions are essential tools for Python developers. Formatted printing helps present data in a readable and user-friendly way, while regular expressions provide powerful text manipulation capabilities. By understanding and using these tools effectively, you can greatly enhance the efficiency and clarity of your Python programs.

Click here to Download Python

Leave a Comment