String Methods
Overview
Because strings are incredibly common in programming, Python equips them with a massive arsenal of built-in methods for formatting, searching, splitting, and sanitizing text. Importantly, because strings are immutable, none of these methods modify the original string in place; they all construct and return a brand new string. These methods are heavily chained together to clean raw, unstructured data (like web forms or CSV files) before processing.
Syntax
text = " Python is AWESOME! "
# Sanitizing (Removing whitespace)
clean_text = text.strip() # "Python is AWESOME!"
# Changing case
print(clean_text.lower()) # "python is awesome!"
print(clean_text.upper()) # "PYTHON IS AWESOME!"
# Searching and Replacing
print(clean_text.startswith("Py")) # True
print(clean_text.replace("AWESOME", "FUN")) # "Python is FUN!"
# Splitting and Joining
words = clean_text.split() # ['Python', 'is', 'AWESOME!']
joined_str = "-".join(words) # "Python-is-AWESOME!"Common Pitfalls
- Calling a method but forgetting to reassign the result to a variable. Running
text.strip()alone does absolutely nothing to thetextvariable. - Using
split("")in an attempt to split a string into individual characters. Python does not support this; you must uselist(text)to get character elements.
Interview Questions
split() behave if you do not provide any arguments?By default, split() breaks the string on any whitespace (spaces, tabs, newlines) and automatically ignores and removes empty strings from the resulting list.
Real-World Example
Cleaning and normalizing dirty email input from a user registration form.
raw_email_input = " NewUser@EXAMPLE.com \n "
# Chain methods to sanitize: strip spaces/newlines, and convert to lowercase
normalized_email = raw_email_input.strip().lower()
print(normalized_email) # "newuser@example.com"Check Your Knowledge
Test your understanding of String Methods with these quick questions.