17/20
Advanced String Methods Β· Page 1 of 1

String Methods & Regular Expressions

Advanced String Methods

String Manipulation Methods

Strings have powerful built-in methods for cleaning and transforming data:

text = "  Hello, World!  "

text.strip()              # "Hello, World!"  β€” remove whitespace
text.replace("World", "Python")  # "Hello, Python!"
text.find("World")        # 8 β€” index of first occurrence
text.startswith("Hello")  # True
text.split(", ")          # ["Hello", "World!"]
text.upper()              # "HELLO, WORLD!"
text.lower()              # "hello, world!"

Working with Regular Expressions (regex)

The re module provides pattern matching for complex text operations:

import re

text = "Email: alice@example.com, bob@test.org"

# Find all emails
emails = re.findall(r"[\w.-]+@[\w.-]+\.\w+", text)
# Result: ['alice@example.com', 'bob@test.org']

# Replace patterns
cleaned = re.sub(r"\d+", "[NUMBER]", "ID-12345-XYZ-678")
# Result: "ID-[NUMBER]-XYZ-[NUMBER]"

# Match at start
if re.match(r"^[A-Z]", "Apple"):
    print("Starts with capital letter!")

Data cleaning gold: Use regex to validate emails, phone numbers, URLs, and extract patterns from messy text.

main.py
Loading...
OUTPUT
β–ΆClick "Run Code" to execute…