Searching and replacing text

Python:
Searching and replacing text

How to:

# Using str.replace() for simple replacement
text = "I like Python. Python is awesome!"
text = text.replace("Python", "programming")
print(text)  # Output: I like programming. programming is awesome!

# Using re.sub() for pattern-based replacement with regex
import re
text = "Contact us at [email protected]"
new_text = re.sub(r'\b[a-zA-Z0-9.-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b', '[email protected]', text)
print(new_text)  # Output: Contact us at [email protected]

Deep Dive

In the early days of programming, text editing was a manual slog. Enter regex (regular expressions), built-in the 1950s, making searching a less headache-inducing affair. For simple replaces, str.replace() is your go-to. It’s straightforward and great for one-off replacements. When you’ve got patterns, like phone numbers, emails, or dates, regex with re.sub() is the magic wand. It finds patterns with a special syntax and swaps them out. Keep in mind, regex can be as quirky as it’s powerful; it’s a tool where you get better the more puzzles you solve.

See Also