Web Analytics

String Methods

Beginner ~35 min read

Python strings come with over 40 built-in methods that make text manipulation easy. This lesson covers the most important methods for case conversion, searching, splitting/joining, and validation.

Remember: Strings are immutable. All string methods return a new string; the original is unchanged. You must assign the result to a variable to keep it.

Case Conversion Methods

These methods change the case of characters in a string.

Method Description Example
upper()All uppercase"hello".upper() โ†’ "HELLO"
lower()All lowercase"HELLO".lower() โ†’ "hello"
capitalize()First char uppercase"hello".capitalize() โ†’ "Hello"
title()Each word capitalized"hello world".title() โ†’ "Hello World"
swapcase()Swap upper/lower"Hello".swapcase() โ†’ "hELLO"
casefold()Aggressive lowercase"StraรŸe".casefold() โ†’ "strasse"
Output
Click Run to execute your code
Best Practice: Use lower() or casefold() for case-insensitive comparisons. casefold() handles special characters better for international text.

Search Methods

These methods help you find and count substrings within strings.

Method Description Not Found
find(sub)Index of first occurrenceReturns -1
rfind(sub)Index of last occurrenceReturns -1
index(sub)Like find()Raises ValueError
count(sub)Count occurrencesReturns 0
startswith(prefix)Check startReturns False
endswith(suffix)Check endReturns False
find() vs index(): Use find() when missing substrings are expected (returns -1). Use index() when the substring should always exist (raises error if not).

Modification Methods

These methods return modified versions of strings - perfect for cleaning, formatting, and transforming text.

Output
Click Run to execute your code
split() and join() are opposites: "a,b,c".split(",") โ†’ ["a", "b", "c"]
",".join(["a", "b", "c"]) โ†’ "a,b,c"

Validation Methods

These methods check the content of strings and return True or False.

Method Returns True If
isalpha()All characters are letters (a-z, A-Z)
isdigit()All characters are digits (0-9)
isalnum()All characters are letters or digits
isspace()All characters are whitespace
isupper()All cased characters are uppercase
islower()All cased characters are lowercase
istitle()String is titlecased
isnumeric()All characters are numeric (includes ยฝ, ยฒ, etc.)
isdecimal()All characters are decimal digits
Output
Click Run to execute your code
Empty String Note: Most is*() methods return False for empty strings, since there are no characters to check.

Common Mistakes

1. Forgetting that methods return new strings

name = "john"
name.upper()  # Returns "JOHN" but doesn't save it!
print(name)   # Still "john"

# Correct:
name = name.upper()
print(name)   # "JOHN"

2. Using find() result without checking

text = "Hello World"
pos = text.find("Python")  # Returns -1

# Wrong: using -1 as an index
print(text[pos])  # Prints 'd' (last char, not what you want!)

# Correct: check first
if pos != -1:
    print(text[pos])
else:
    print("Not found")

3. Calling join() on the wrong object

words = ["Hello", "World"]

# Wrong:
# words.join(" ")  # AttributeError: list has no join()

# Correct: call join on the separator
result = " ".join(words)  # "Hello World"

4. Using split() without argument vs with space

text = "  Hello   World  "

# split() with no arg - splits on any whitespace, removes empty
text.split()      # ['Hello', 'World']

# split(' ') - splits only on single space, keeps empty strings
text.split(' ')   # ['', '', 'Hello', '', '', 'World', '', '']

Exercise: String Methods Practice

Task: Use string methods to process and validate text data.

Requirements:

  • Clean and transform text using case and strip methods
  • Search for and count substrings
  • Split and join strings
  • Validate string content
Output
Click Run to execute your code
Show Solution
text = "   Python Programming Language   "
email = "[email protected]"
csv_data = "apple,banana,cherry,date"
words_list = ["Hello", "World", "Python"]

# 1. Strip and uppercase
print(text.strip().upper())  # 'PYTHON PROGRAMMING LANGUAGE'

# 2. Lowercase email
print(email.lower())  # '[email protected]'

# 3. Count 'a' in csv_data
print(csv_data.count('a'))  # 4

# 4. Check if ends with .com (case-insensitive)
print(email.lower().endswith('.com'))  # True

# 5. Split csv_data
print(csv_data.split(','))  # ['apple', 'banana', 'cherry', 'date']

# 6. Join words_list
print(' - '.join(words_list))  # 'Hello - World - Python'

# 7. Replace commas with semicolons
print(csv_data.replace(',', ';'))  # 'apple;banana;cherry;date'

# 8. Check if 'Programming' is in text
print('Programming' in text.strip())  # True

Quick Reference

Case Methods: upper(), lower(), capitalize(), title(), swapcase()

Search Methods: find(), rfind(), index(), count(), startswith(), endswith()

Modify Methods: replace(), strip(), lstrip(), rstrip(), split(), join()

Check Methods: isalpha(), isdigit(), isalnum(), isspace(), isupper(), islower()

Padding: center(), ljust(), rjust(), zfill()

What's Next?

In the next lesson, we'll explore booleans - Python's logical data type for representing True and False values, including truthy/falsy concepts and comparisons.