String Methods
Master strip(), lower(), upper(), replace(), startswith(), and find() through practical examples, exact outputs, and beginner-friendly exercises.
In this lesson, you will learn
- ✓Explain what strip(), lower(), upper(), replace(), startswith(), and find() do.
- ✓Use string methods to remove surrounding whitespace, change letter case, and replace text.
- ✓Check string prefixes and search for substrings using startswith() and find().
- ✓Understand return values, case sensitivity, missing substrings, and optional method arguments.
- ✓Explain why string methods return new values rather than modifying the original string.
- ✓Trace method calls in execution order and predict their exact output.
1. Understanding string methods
A string method is an operation associated with a string object. You call a method by writing the string or variable, a dot, the method name, and parentheses when required. For example, text.lower() calls the lower() method on the string referenced by text.
Methods can return different kinds of values. lower(), upper(), strip(), and replace() return strings. startswith() returns a Boolean value, True or False. find() returns an integer representing a position, or -1 if the requested substring is not found.
A string method usually does not change the original string. Python strings are immutable, so methods such as lower() and replace() return new string values. If you want to keep the result, assign it to a variable or use it directly.
You can also chain method calls. For example, text.strip().lower() first removes surrounding whitespace and then converts the resulting string to lowercase. Python evaluates the method calls from left to right in this expression.
Call string methods
The variable text refers to a string with two spaces at each end. strip() returns a string without leading and trailing whitespace. lower() converts the letters in that returned string to lowercase. The first print() displays the chained result. The second print() displays the original string, which has not changed.
Note
2. Remove surrounding whitespace with strip()
The strip() method returns a string with leading and trailing whitespace removed. Leading whitespace appears before the first non-whitespace character, while trailing whitespace appears after the last non-whitespace character.
By default, strip() removes whitespace such as spaces, tabs, and newline characters from both ends. It does not remove whitespace from the middle of a string.
The related methods lstrip() and rstrip() remove leading whitespace and trailing whitespace, respectively. Use them when you need to clean only one side.
strip() can also accept a string of characters to remove from both ends. In that case, Python removes any matching characters repeatedly from either end until it reaches a character that is not in the supplied set. The argument is not treated as one exact substring.
An empty string remains empty after strip(). If the string contains only whitespace, strip() returns an empty string.
Remove spaces from both ends
The first print() displays the string after surrounding spaces are removed. The spaces between 'Hello' and 'Python' remain because strip() does not remove internal whitespace. The original text remains unchanged, as shown by the second print().
Note
3. Change letter case with lower() and upper()
The lower() method returns a lowercase version of a string. For example, 'PYTHON'.lower() returns 'python'.
The upper() method returns an uppercase version of a string. For example, 'Python'.upper() returns 'PYTHON'.
These methods are useful for normalizing text before comparison. For example, converting two words to lowercase lets you compare their lowercase forms without differences in letter case affecting the comparison.
lower() and upper() do not remove spaces, punctuation, or digits. They change the case of applicable letters while leaving other characters unchanged.
Both methods return new strings rather than modifying the original string. To save the result, assign it back to a variable or another variable.
Convert text to lowercase and uppercase
lower() converts applicable letters to lowercase. upper() converts applicable letters to uppercase. The space, digits, and exclamation mark remain unchanged.
Note
4. Replace text with replace()
The replace() method returns a string in which occurrences of one substring are replaced with another. Its basic syntax is text.replace(old, new).
The old argument specifies the substring to search for, and the new argument specifies its replacement. By default, replace() replaces all non-overlapping occurrences of the old substring.
The optional third argument, count, limits the number of replacements. For example, text.replace('a', 'o', 1) replaces only the first occurrence of 'a'. A count of 0 performs no replacements.
Replacement is case-sensitive. Calling 'Python'.replace('p', 'J') does not replace anything because the string contains an uppercase 'P', not a lowercase 'p'.
If the old substring is not present, replace() returns an equivalent string with no replacements made. The original string is not modified.
Replace every matching occurrence
replace('a', 'o') replaces each occurrence of 'a' with 'o'. The word 'banana' contains three occurrences of 'a', so the result is 'bonono'. The original variable still refers to 'banana'.
Caution
5. Check prefixes with startswith()
The startswith() method checks whether a string begins with a specified prefix. A prefix is text that appears at the beginning of another string.
The method returns True when the string begins with the requested prefix and False otherwise. The comparison is case-sensitive.
For example, 'Python'.startswith('Py') returns True, while 'Python'.startswith('py') returns False.
An empty string is a prefix of every string, including the empty string itself. Therefore, text.startswith('') returns True.
startswith() can also accept a tuple of prefixes. It returns True if the string starts with any one of the supplied prefixes. This can be useful when checking several permitted filename prefixes or protocols.
Check whether a string starts with text
The filename begins with 'report', so the first result is True. The filename does not begin with 'pdf', so the second result is False. The comparison is case-sensitive, so 'Report' does not match the lowercase beginning 'report'.
Note
6. Search for text with find()
The find() method searches for a substring and returns the index of its first occurrence. If the substring is not found, find() returns -1 instead of raising an exception.
The returned index is zero-based. For example, 'banana'.find('na') returns 2 because the first occurrence of 'na' begins at index 2.
If a substring occurs more than once, find() returns the position of the first occurrence. It does not return every matching position.
find() accepts optional start and end arguments that limit the search range. The end boundary is excluded, following Python's usual slicing convention.
The search is case-sensitive. For example, 'Python'.find('p') returns -1 because lowercase 'p' does not occur in the string.
Do not confuse find() with index(). Both can return the position of a matching substring, but index() raises ValueError when the substring is missing, while find() returns -1.
Find a substring
The first 'na' begins at index 2, so find('na') returns 2. The first 'a' appears at index 1, so find('a') returns 1. The character 'z' is not present, so find('z') returns -1.
Caution
7. A complete dry run: clean and search text
String methods can be combined to prepare text and then inspect it. A common sequence is to remove surrounding whitespace, convert text to a consistent case, and search for a particular word.
When tracing chained operations, evaluate each method in order. Keep track of the returned value at every stage, and remember that the original string remains unchanged unless you assign a new value to the variable.
Clean a string and find a word
The original text contains spaces at both ends and uses uppercase letters. strip() removes the surrounding spaces, and lower() converts the text to 'learn python'. startswith('learn') returns True because the cleaned string begins with 'learn'. find('python') returns 6 because 'python' starts at index 6 in 'learn python'. The final print() confirms that the original text has not changed.
Note
8. Practical use and edge cases
When processing user input, strip() can remove accidental spaces around a username or search term. lower() can normalize case before a simple case-insensitive comparison.
Use startswith() to check a prefix, such as a known label at the beginning of a line. Use find() when you need the position of a substring or need to know whether it appears.
Empty strings are valid inputs to these methods. For example, ''.strip() and ''.lower() return empty strings, ''.startswith('') returns True, and ''.find('x') returns -1.
If you call replace() with an empty old substring, Python inserts the replacement between characters and at both ends. This is valid behavior, but it may not be what you intend.
String methods are case-sensitive unless their behavior or the surrounding code explicitly accounts for case. Normalize text first when that matches the requirement.
For simple case-insensitive checks, converting both strings to the same case is often sufficient. For broader Unicode-aware case-insensitive comparisons, consider casefold() rather than assuming lower() handles every language's casing rules identically.
Handle an empty string
strip() returns the empty string, so the first print() produces a blank line. Every string begins with the empty prefix, so startswith('') returns True. The character 'x' is absent, so find('x') returns -1.
Caution
Common pitfalls to avoid
Real debugging lessons and exact syntax contrasts to avoid runtime bugs
#1 Assuming strip() removes every space in a string.
Why it happens: strip() removes leading and trailing characters from a set of characters; it does not remove every internal space.
Key takeaway: strip() removes whitespace from the beginning and end only. Use an appropriate replacement or splitting operation if internal whitespace must also change.
#2 Expecting lower() or upper() to modify the original string.
Why it happens: Strings are immutable, so lower() and upper() return transformed strings rather than changing the original string in place.
Key takeaway: String methods return new string values. Assign the result if you want the variable to refer to the transformed string.
#3 Assuming replace() changes only the first occurrence.
Why it happens: replace() replaces all matching occurrences by default; use its count argument to limit how many replacements occur.
Key takeaway: By default, replace() replaces all non-overlapping occurrences. Supply the optional count argument to limit the number of replacements.
#4 Ignoring case when using replace(), startswith(), or find().
Why it happens: String searches and replacements are case-sensitive by default, so text with different capitalization may not match.
Key takeaway: These operations are case-sensitive. Normalize the text first if the task requires case-insensitive matching.
#5 Thinking startswith() searches anywhere in a string.
Why it happens: startswith() checks the beginning of a string, not arbitrary positions within it.
Key takeaway: startswith() checks only the beginning. Use find() or the in operator when you need to search within the string.
#6 Assuming find() raises an exception when text is missing.
Why it happens: find() returns -1 when the substring is absent instead of raising an exception.
Key takeaway: find() returns -1 when the substring is not found. The index() method raises ValueError in that situation.
#7 Using the result of find() as a Boolean without checking it.
Why it happens: A find() result of 0 means a match begins at the first character, while -1 means no match; test against -1 rather than relying on truthiness.
Key takeaway: Check position != -1 to test whether a substring was found. A valid match can occur at index 0, which is a falsy integer in a Boolean context.
#8 Treating strip('abc') as removal of the exact substring 'abc'.
Why it happens: strip('abc') removes any leading or trailing characters that belong to the set a, b, or c; it does not remove the exact substring 'abc' as a unit.
Key takeaway: The argument to strip() is a set of characters to remove repeatedly from both ends, not an exact substring.
Ready for hands-on challenges?
Test your skills with shuffled coding challenges in the Practice Arena.
Technical and placement interview questions
Frequently tested interview questions with detailed, full answers (click to expand)
Q1:What is a string method in Python?
Q2:What is the difference between strip(), lstrip(), and rstrip()?
Q3:What is the difference between lower() and upper()?
Q4:How does replace() work, and what is its optional count argument?
Q5:What does startswith() return?
Q6:What does find() return when a substring is not present?
Q7:Why does text.lower() not permanently change text?
Q8:How would you perform a simple case-insensitive comparison?
Key takeaways
- strip() removes surrounding whitespace by default; lstrip() and rstrip() remove it from one side.
- lower() and upper() return lowercase and uppercase versions of a string.
- replace(old, new) replaces all non-overlapping occurrences by default; an optional count limits replacements.
- startswith() checks whether a string begins with a prefix and returns True or False.
- find() returns the first matching substring's zero-based position, or -1 when it is absent.
- String matching with these methods is case-sensitive unless you explicitly normalize the text.
- Python strings are immutable, so string methods return new values rather than modifying the original string.
- Identify each method's return type and check edge cases such as empty strings and missing substrings.
Related Topics & Next Steps
4 Recommended LessonsStrengthen your Python foundation with these complementary core lessons: