How to use re.sub() function in Python

1 Answer

0 votes
"""
Idiomatic demonstration of re.sub() in Python.

IMPORTANT:
To avoid SyntaxWarning: invalid escape sequence inside docstrings,
we escape backslashes like this:

    \\d   → literal backslash + d (digit class)
    \\s+  → literal backslash + s+ (whitespace class)

Regex patterns themselves MUST remain raw strings:
    r"\\d"
    r"\\s+"
"""

import re

def mask_digits(text):
    """
    Replace every digit with 'X'.
    Pattern \\d matches any digit.
    """
    return re.sub(r"\d", "X", text)


def normalize_whitespace(text):
    """
    Replace any sequence of whitespace with a single space.
    Pattern \\s+ matches one or more whitespace characters.
    """
    return re.sub(r"\s+", " ", text).strip()


def emphasize_words(text):
    """
    Wrap each word in brackets using a function replacement.
    Pattern \\w+ matches a word.
    """
    def repl(match):
        return f"[{match.group(0)}]"
    return re.sub(r"\w+", repl, text)


def square_numbers(text):
    """
    Square every integer found in the text.
    Pattern \\d+ matches one or more digits.
    """
    def square(match):
        number = int(match.group(0))
        return str(number ** 2)
    return re.sub(r"\d+", square, text)


# ------------------------------
# Usage
# ------------------------------

sample = "User42 logged in   at 10:30.\nNew session started."

masked = mask_digits(sample)
normalized = normalize_whitespace(sample)
emphasized = emphasize_words("Hello Selene, welcome to Python!")
squared = square_numbers("1 2 3 4 5 6 7 8 9")

print("Masked digits:", masked)
print("Normalized whitespace:", normalized)
print("Emphasized words:", emphasized)
print("Squared numbers:", squared)



'''
run:

Masked digits: UserXX logged in   at XX:XX.
New session started.
Normalized whitespace: User42 logged in at 10:30. New session started.
Emphasized words: [Hello] [Selene], [welcome] [to] [Python]!
Squared numbers: 1 4 9 16 25 36 49 64 81

'''

 



answered 11 hours ago by avibootz

Related questions

1 answer 168 views
1 answer 200 views
1 answer 122 views
1 answer 196 views
...