Modify Strings
String Methods
Strings in Python are immutable, meaning their contents cannot be changed in place. However, methods return new modified strings based on the original.
Example
text = " hello World! "
# Common modifications
upper = text.upper() # ' HELLO WORLD! '
lower = text.lower() # ' hello world! '
stripped = text.strip() # 'hello World!'
replaced = text.replace("World", "Python")
print(upper)
print(lower)
print(stripped)
print(replaced)
Output
HELLO WORLD! hello world! hello World! hello Python!
Case Conversion
Several built-in methods help with changing the case of strings. These are often used in formatting and text normalization.
Method | Description | Example |
---|---|---|
upper() | Convert all characters to uppercase | "hello".upper() → 'HELLO' |
lower() | Convert all characters to lowercase | "Hello".lower() → 'hello' |
title() | Capitalize the first letter of each word | "hello world".title() → 'Hello World' |
capitalize() | Capitalize only the first character | "hello".capitalize() → 'Hello' |
swapcase() | Swap the case of all characters | "HeLLo".swapcase() → 'hEllO' |
Practical Examples
String modification is often applied when processing user input or preparing output. Common tasks include trimming whitespace, changing case for comparisons, and formatting messages with dynamic values.
Example
# Cleaning user input
user_input = " UsERnaME "
clean_input = user_input.strip().lower()
print(clean_input) # 'username'
# Template replacement
template = "Hello {name}, your score is {score}"
personalized = template.format(name="Alice", score=95)
print(personalized) # 'Hello Alice, your score is 95'
ℹ️ Note: Always normalize strings before comparing or storing them to ensure consistency.