String Formatting

Python provides several ways to format strings, including string concatenation, string formatting operators, and f-strings (formatted string literals).

name = "Alice"
age = 25
String concatenation
message = "Hello, " + name + ". You are " + str(age) + " years old."
print(message)  # Output: Hello, Alice. You are 25 years old.
String formatting operator (%)
message = "Hello, %s. You are %d years old." % (name, age)
print(message)  # Output: Hello, Alice. You are 25 years old.
f-strings (Python 3.6+)
message = f"Hello, {name}. You are {age} years old."
print(message)  # Output: Hello, Alice. You are 25 years old.

String Methods

Python strings provide various built-in methods for performing common operations, such as finding substrings, replacing text, splitting strings, and more.

message = "Hello, world!"
print(message.upper())     # Output: HELLO, WORLD!
print(message.lower())     # Output: hello, world!
print(message.replace("world", "Python"))  # Output: Hello, Python!
words = message.split(",")  # Output: ['Hello', ' world!']
print(words)
name = "  Alice  "
print(name.strip())        # Output: Alice

Regular Expressions

Regular expressions are powerful patterns used for advanced string matching and manipulation. Python provides the re module for working with regular expressions.

import re
text = "The cat sat on the mat. The dog chased the cat."
Search for a pattern
match = re.search(r"cat", text)
print(match.group())  # Output: cat
Find all occurrences of a pattern
matches = re.findall(r"cat|dog", text)
print(matches)  # Output: ['cat', 'cat', 'dog']
Substitute a pattern
new_text = re.sub(r"cat", "mouse", text)
print(new_text)  # Output: The mouse sat on the mat. The dog chased the mouse.

In the next chapter, we'll explore functional programming concepts in Python, including lambda functions, map, filter, and reduce, as well as list comprehensions and generator expressions.