Before we start, you must remember one thing: strings are immutable. This means they cannot be changed once they are created.
When you use a method like .replace(), Python doesn’t edit the original string, it creates a brand-new copy with the changes. If you want to keep the change, you must overwrite the old variable.
name = "daniel"
# This does nothing to the 'name' variable
name.upper()
# This works! We save the new copy over the old one
name = name.upper()
print(name) # DANIEL
.join()
This is one of the most used methods in Python. It takes a list of words and glues them together into one string.
The Syntax: "separator".join(list)
You specify the separator once at the beginning (like a space, a comma, or a dash), and Python puts it between every item in the list.
words = ["The", "Fool", "Moretti"]
# Glue them together with a space
full_name = " ".join(words)
print(full_name) # "The Fool Moretti"
# Glue them together with a dash
url_slug = "-".join(words)
print(url_slug) # "The-Fool-Moretti"
.split()
The .split() method is the exact opposite of .join(). It takes a string and breaks it into a list. By default, it splits by whitespace (spaces, tabs, newlines).
sentence = "Python is amazing"
words = sentence.split()
print(words) # ['Python', 'is', 'amazing']
You can also split by a specific character, like a comma:
data = "Apple,Banana,Cherry"
fruits = data.split(",")
print(fruits) # ['Apple', 'Banana', 'Cherry']
.find()
If you need to know where a specific character or word starts, use .find(). It returns the index (the position number) of the first time it sees that text.
If the text is not found, .find() returns -1.
text = "Lord of the Mysteries"
print(text.find("e")) # 9 (The 'e' in 'the')
print(text.find("Z")) # -1 (Not found)
.replace()
Use .replace() to swap one piece of text for another. By default, it replaces every instance it finds.
message = "I hate features. Features are the worst."
clean_message = message.replace("features", "bugs").replace("Features", "Bugs")
print(clean_message) # "I hate bugs. Bugs are the worst."
Useful “Cleaner” Methods
When taking input from users, they often add accidental spaces. These methods help clean that up:
.strip(): Removes all whitespace from the start and end..lower(): Makes everything lowercase (great for comparing strings)..upper(): Makes everything uppercase..title(): Capitalizes the first letter of every word.
You can stack these methods in one line. Python runs them from left to right.
stored_email = "daniel@example.com"
user_input = " DANIEL@Example.com "
# Without cleaning, this is False
print(user_input == stored_email) # False
# With cleaning
# .strip() removes the " " and .lower() handles the "DANIEL"
if user_input.strip().lower() == stored_email:
print("1 user found.") # This runs!
Another example:
user_input = " daNIel "
clean_name = user_input.strip().title()
print(f"'{clean_name}'") # 'Daniel'