Essential String Methods
15 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Strings come equipped with rich built-in transformation methods. Because strings are immutable, every string method returns a new string object.
Cleaning text with strip()
String method is a function that belongs to a string and is called with a dot, like text.strip(). Strings are immutable, so a method returns a new string and leaves the original unchanged.
Use .strip() to remove leading and trailing whitespace, or pass specific characters to strip.
raw_input = " user@domain.com\n"clean = raw_input.strip()print(f"'{clean}'")Example 1 · Cleaning an email field
raw = " Priya.N@Example.COM \n"email = raw.strip().lower()print(repr(raw))print(email)print(len(raw), len(email))' Priya.N@Example.COM \n' priya.n@example.com 23 19
What this code does
strip()removes the spaces and the newline at both ends.lower()makes the address lower case.rawitself is not changed.reprshows the hidden characters in the original.
Removes spaces and trailing newline characters, producing 'user@domain.com'.
Case transformations
Normalisation is changing text into one standard form, such as lower case with no extra spaces, so that two different spellings compare as equal.
Standardize text for case-insensitive comparisons using .lower(), .upper(), and .title().
role = "Admin"if role.lower() == "admin": print("Role verified")Example 2 · Comparing roles without caring about case
entered = "ADMIN"stored = "admin"print(entered == stored)print(entered.lower() == stored.lower())print("order shipped".title())False True Order Shipped
What this code does
- Two strings with different capitals are not equal.
- Making both lower case first gives a fair comparison.
title()is handy for showing names.
Comparing role.lower() prevents false negatives caused by mixed capitalization like 'ADMIN' or 'admin'.
Replacing and counting text
Substring is a run of characters inside a string. replace() swaps one substring for another, and count() tells how many times a substring appears.
Use .replace(old, new) to swap substrings, and .count(sub) to count occurrences.
message = "Java is powerful. Java is popular."updated = message.replace("Java", "Python")print(updated)print(updated.count("Python"))Example 3 · Tidying a page title
headline = " mastering modern python backend "cleaned = headline.strip().title()summary = cleaned.replace("Backend", "APIs")
print(cleaned)print(summary)Mastering Modern Python Backend Mastering Modern Python APIs
What this code does
headline.strip().title()capitalizes each word: 'Mastering Modern Python Backend'..replace('Backend', 'APIs')updates the topic to 'Mastering Modern Python APIs'.
The console displays the replaced string and confirms that 'Python' appears twice.
Next step
Check your understanding
9 quick questions