PythonString Methods

String Methods

Because strings are objects, they come with a large set of built-in methods for transforming, searching, and inspecting text. All of these methods return a new string (or other value) rather than modifying the original, since strings are immutable.

Changing Case

Python
text = "Hello, World!"

print(text.upper())       # HELLO, WORLD!
print(text.lower())       # hello, world!
print(text.title())       # Hello, World!
print(text.capitalize())  # Hello, world!
print(text.swapcase())    # hELLO, wORLD!
Note
`.title()` capitalizes the first letter of every word, while `.capitalize()` capitalizes only the very first letter of the whole string and lowercases the rest.
Stripping Whitespace

.strip(), .lstrip(), and .rstrip() remove leading/trailing whitespace (or any characters you specify) — extremely common when cleaning up user input or lines read from a file.

Python
raw = "   padded text   \n"

print(repr(raw.strip()))   # 'padded text'
print(repr(raw.lstrip()))  # 'padded text   \n'
print(repr(raw.rstrip()))  # '   padded text'

# strip() can also remove specific characters, not just whitespace
print("***important***".strip("*"))  # important
Splitting and Joining

.split() breaks a string into a list of pieces, and .join() does the reverse, stitching a list of strings back together with a given separator.

Python
sentence = "the quick brown fox"
words = sentence.split()          # splits on any whitespace by default
print(words)                       # ['the', 'quick', 'brown', 'fox']

csv_row = "id,name,email"
fields = csv_row.split(",")        # split on a specific separator
print(fields)                       # ['id', 'name', 'email']

rejoined = "-".join(fields)
print(rejoined)                     # id-name-email

print(" ".join(words))              # the quick brown fox
Tip
`''.join(list_of_strings)` is the idiomatic, fast way to build a long string from many pieces — much better than repeatedly concatenating with `+` inside a loop.
Replacing Text

Python
sentence = "I like cats. Cats are great."
print(sentence.replace("Cats", "Dogs"))
# I like cats. Dogs are great.

# An optional third argument limits how many replacements happen
print("aaaa".replace("a", "b", 2))  # bbaa
Searching Inside a String

.find() and .index() both locate the position of a substring, but they differ in how they handle a “not found” result.

Python
text = "learning python is fun"

print(text.find("python"))   # 9  -- index where "python" starts
print(text.find("java"))     # -1 -- not found, returns -1 (no exception)

print(text.index("python"))  # 9  -- same as find() when the substring exists
# text.index("java")          # ValueError: substring not found -- raises instead!
Note
Use `.find()` when a missing substring is a normal, expected case (you just check for `-1`). Use `.index()` when a missing substring should be treated as an error you want to surface with an exception.
Checking Prefixes, Suffixes, and Counting

Python
filename = "report_final.pdf"

print(filename.startswith("report"))  # True
print(filename.endswith(".pdf"))       # True
print(filename.endswith((".pdf", ".docx")))  # True -- can pass a tuple of options

text = "mississippi"
print(text.count("s"))    # 4
print(text.count("ss"))   # 2 (non-overlapping matches)
Checking Character Composition

A family of .is...() methods let you check what kind of characters a string contains — handy for validating input.

Python
print("12345".isdigit())    # True
print("abc123".isdigit())   # False
print("abc".isalpha())      # True
print("abc123".isalnum())   # True -- letters AND digits, no symbols
print("   ".isspace())      # True
print("HELLO".isupper())    # True
print("hello".islower())    # True
Quick Reference: Most-Used String Methods

Method

Description

.upper() / .lower()

Convert to all uppercase / all lowercase.

.title() / .capitalize()

Capitalize each word / capitalize just the first letter.

.strip() / .lstrip() / .rstrip()

Remove leading/trailing whitespace (or given characters).

.split(sep)

Break a string into a list using a separator.

.join(iterable)

Combine an iterable of strings using this string as the separator.

.replace(old, new)

Return a copy with all (or limited) occurrences replaced.

.find(sub) / .index(sub)

Locate a substring; find() returns -1, index() raises if missing.

.startswith(x) / .endswith(x)

Check if the string starts or ends with a given value.

.count(sub)

Count non-overlapping occurrences of a substring.

.isdigit() / .isalpha() / .isalnum()

Check whether the string is all digits / letters / letters+digits.

Method Chaining

Because every string method returns a new string, calls can be chained one after another for a compact pipeline of transformations.

Python
messy = "   Hello, WORLD!   "
clean = messy.strip().lower().replace("!", ".")
print(clean)  # hello, world.