Skip to content
PythonStrings and Textbeginner18 min read

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

Call string methods
python
text = ' Hello Python '
print(text.strip().lower())
print(text)
Output
hello python Hello Python

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

Before using a method, identify its return type. A string-returning method, a Boolean method, and a method that returns an integer cannot be used interchangeably.

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

Remove spaces from both ends
python
text = ' Hello Python '
print(text.strip())
print(text)
Output
Hello Python Hello Python

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

Use strip() to remove surrounding whitespace, not to remove every space in a sentence. For example, ' Hello World '.strip() produces 'Hello World', preserving the internal space.

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

Convert text to lowercase and uppercase
python
text = 'Hello Python 123!'
print(text.lower())
print(text.upper())
Output
hello python 123! HELLO PYTHON 123!

lower() converts applicable letters to lowercase. upper() converts applicable letters to uppercase. The space, digits, and exclamation mark remain unchanged.

Note

Converting both strings to the same case is a common beginner-friendly technique for case-insensitive comparisons. Python also provides casefold() for more comprehensive Unicode-aware caseless comparisons.

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 every matching occurrence
python
text = 'banana'
print(text.replace('a', 'o'))
print(text)
Output
bonono banana

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

replace() does not modify the original string in place. If you need to keep the changed value, use text = text.replace('old', 'new').

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

Check whether a string starts with text
python
filename = 'report.pdf'
print(filename.startswith('report'))
print(filename.startswith('pdf'))
print(filename.startswith('Report'))
Output
True False False

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

Use startswith() when the beginning of a string matters. Use in when you want to check whether a substring appears anywhere in the string.

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

Find a substring
python
text = 'banana'
print(text.find('na'))
print(text.find('a'))
print(text.find('z'))
Output
2 1 -1

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

Do not treat -1 as a valid match position. If find() returns -1, the requested substring was not found.

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

Clean a string and find a word
python
text = ' Learn Python '
cleaned = text.strip().lower()
print(cleaned)
print(cleaned.startswith('learn'))
print(cleaned.find('python'))
print(text)
Output
learn python True 6 Learn Python

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

Method chaining does not automatically overwrite the original variable. The result changes only if you assign it, as in cleaned = text.strip().lower().

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

Handle an empty string
python
text = ''
print(text.strip())
print(text.startswith(''))
print(text.find('x'))
Output
True -1

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

Before choosing a string method, decide whether you need a transformed string, a Boolean test, or a search position. For example, find() returns an integer, while startswith() returns a Boolean.

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.

Incorrect Approach
script.py
python
Assuming strip() removes every space in a string.
Correct Solution
script.py
python
strip() removes whitespace from the beginning and end only. Use an appropriate replacement or splitting operation if internal whitespace must also change.

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.

Incorrect Approach
script.py
python
Expecting lower() or upper() to modify the original string.
Correct Solution
script.py
python
String methods return new string values. Assign the result if you want the variable to refer to the transformed string.

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.

Incorrect Approach
script.py
python
Assuming replace() changes only the first occurrence.
Correct Solution
script.py
python
By default, replace() replaces all non-overlapping occurrences. Supply the optional count argument to limit the number of replacements.

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.

Incorrect Approach
script.py
python
Ignoring case when using replace(), startswith(), or find().
Correct Solution
script.py
python
These operations are case-sensitive. Normalize the text first if the task requires case-insensitive matching.

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.

Incorrect Approach
script.py
python
Thinking startswith() searches anywhere in a string.
Correct Solution
script.py
python
startswith() checks only the beginning. Use find() or the in operator when you need to search within the string.

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.

Incorrect Approach
script.py
python
Assuming find() raises an exception when text is missing.
Correct Solution
script.py
python
find() returns -1 when the substring is not found. The index() method raises ValueError in that situation.

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.

Incorrect Approach
script.py
python
Using the result of find() as a Boolean without checking it.
Correct Solution
script.py
python
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.

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.

Incorrect Approach
script.py
python
Treating strip('abc') as removal of the exact substring 'abc'.
Correct Solution
script.py
python
The argument to strip() is a set of characters to remove repeatedly from both ends, not an exact substring.

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.

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?
Answer:
A string method is an operation called on a string using dot notation, such as text.lower(). String methods can return transformed strings, Boolean results, or other values depending on the method.
Q2:What is the difference between strip(), lstrip(), and rstrip()?
Answer:
strip() removes leading and trailing whitespace by default. lstrip() removes leading whitespace, while rstrip() removes trailing whitespace. They return new strings and do not modify the original.
Q3:What is the difference between lower() and upper()?
Answer:
lower() returns a lowercase version of a string, while upper() returns an uppercase version. Neither method modifies the original string.
Q4:How does replace() work, and what is its optional count argument?
Answer:
replace(old, new) returns a string with all non-overlapping occurrences of old replaced by new. The optional count argument limits how many replacements are made. The operation is case-sensitive.
Q5:What does startswith() return?
Answer:
startswith(prefix) returns True if the string begins with the specified prefix and False otherwise. The comparison is case-sensitive. It can also accept a tuple of possible prefixes.
Q6:What does find() return when a substring is not present?
Answer:
find() returns -1 when the requested substring is absent. When the substring is found, it returns the zero-based index of its first occurrence. By contrast, index() raises ValueError when the substring is missing.
Q7:Why does text.lower() not permanently change text?
Answer:
Python strings are immutable. lower() returns a new string value, so the original variable remains unchanged unless you assign the result, for example text = text.lower().
Q8:How would you perform a simple case-insensitive comparison?
Answer:
Convert both strings to the same case before comparing them, for example first.lower() == second.lower(). For more comprehensive Unicode-aware caseless comparisons, casefold() may be more appropriate.

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.
Was this lesson helpful?
Found an error? Report an issue

Related Topics & Next Steps

4 Recommended Lessons

Strengthen your Python foundation with these complementary core lessons: