Strings in Python come with built-in methods that let you transform and manipulate text. Think of them as tools for working with words!
Methods are functions that belong to a specific data type. For strings, you use a dot (.) after the variable name:
text = "hello"
result = text.upper().upper() - Make Uppercasemessage = "hello"
print(message.upper()) # HELLO.lower() - Make Lowercasemessage = "HELLO"
print(message.lower()) # helloUse case: Comparing user input
answer = "YES"
if answer.lower() == "yes":
print("You said yes!").replace(old, new) - Replace Textsentence = "I love fish"
new_sentence = sentence.replace("fish", "cats")
print(new_sentence) # I love catsImportant: .replace() creates a new string, it doesn't change the original:
message = "Hello World"
new_message = message.replace("World", "Python")
print(message) # Hello World (unchanged!)
print(new_message) # Hello Python (new string!).strip() - Remove Leading/Trailing Spacesmessy = " hello "
clean = messy.strip()
print(clean) # helloReal use: Cleaning user input
username = input("Enter username: ")
username = username.strip() # Remove accidental spaces
print(username)You can use multiple methods in sequence:
text = " python "
result = text.strip().upper()
print(result) # PYTHONHow it works:
text.strip() → "python""python".upper() → "PYTHON"name = " Alice SMITH "
clean_name = name.strip().lower()
print(f"Welcome, {clean_name}!")city = "copenhagen"
proper_city = city.upper()
print(proper_city) # COPENHAGENtemplate = "Hello NAME, welcome to CITY!"
personalized = template.replace("NAME", "Vidar")
personalized = personalized.replace("CITY", "Copenhagen")
print(personalized) # Hello Vidar, welcome to Copenhagen!filename = "My Document.txt"
clean_filename = filename.replace(" ", "_").lower()
print(clean_filename) # my_document.txtNormalize text for comparison:
user_input = " YES "
if user_input.strip().lower() == "yes":
print("Confirmed!")Format display text:
product = "laptop computer"
display = product.upper()
print(f"Product: {display}")Clean and validate:
email = " User@Example.COM "
clean_email = email.strip().lower()
print(f"Email: {clean_email}")| Method | What It Does | Example |
|--------|-------------|---------|
| .upper() | ALL CAPS | "hi".upper() → "HI" |
| .lower() | all lowercase | "HI".lower() → "hi" |
| .strip() | Remove spaces from ends | " hi ".strip() → "hi" |
| .replace(old, new) | Replace text | "hi".replace("h", "b") → "bi" |
" PYTHON " → "python"" hello world " and make it "HELLO WORLD".replace()clean = messy.strip()text.strip().upper().upper() not .Upper()Ready to work with collections of data? Learn about Lists and For Loops next!