Python’s built-in string methods (often called “string functions”) let you manipulate text directly—searching, splitting, changing case, stripping whitespace, and more—without importing any module. This article covers the full list of Python’s built-in string methods, how they work, and when to use each one.
What Are String Methods in Python?
In Python, a string is an immutable sequence of Unicode characters. The built-in methods are functions that belong to the str class and are called with dot notation, like text.upper(). They never modify the original string; instead, they return a new string (or a list, or a boolean) with the result. This immutability is important: if you write s = s.strip(), you are rebinding the variable to a new string, not altering the original.
There are over 40 built-in string methods in Python 3.11. They cover case conversion, searching, splitting, joining, padding, formatting, and testing string properties. None require an import—they are always available.
Case Conversion and Checking
The most commonly used methods change or check letter casing:
str.upper()– returns the string in all uppercase.str.lower()– returns the string in all lowercase.str.capitalize()– uppercases the first character, lowercases the rest.str.title()– uppercases the first letter of each word.str.swapcase()– flips uppercase to lowercase and vice versa.str.casefold()– aggressive lowercase for case-insensitive matching (handles German ß, etc.).
For checking, use str.isupper(), str.islower(), str.istitle(). These return True or False. For example, "Hello".istitle() returns True, but "hello".istitle() returns False.
Searching and Finding Substrings
To locate a substring, Python gives you several options:
str.find(sub)– returns the lowest index wheresubis found, or -1 if not found.str.rfind(sub)– returns the highest index (rightmost occurrence).str.index(sub)– likefindbut raisesValueErrorif not found.str.rindex(sub)– rightmost version ofindex.str.count(sub)– counts non-overlapping occurrences.str.startswith(prefix)andstr.endswith(suffix)– return booleans.
All of these accept optional start and end indices to limit the search. For example, "hello world".find("o", 5) returns 7 because it starts searching from index 5.
Splitting, Joining, and Replacing
These methods are essential for data cleaning and text processing:
str.split(sep=None)– splits the string into a list of words. With no argument, it splits on any whitespace and removes empty strings. With a separator, it splits exactly on that separator.str.rsplit(sep=None)– splits from the right; useful for limiting splits.str.splitlines()– splits at line breaks (
,
, etc.).str.join(iterable)– joins an iterable of strings using the string as a separator. For example,"-".join(["a","b","c"])gives"a-b-c".str.replace(old, new, count=-1)– replaces all occurrences (or up tocount).str.strip(),str.lstrip(),str.rstrip()– remove leading/trailing whitespace or specific characters.
Example: "a,b,c".split(",") returns ['a', 'b', 'c']. To split only the first comma, use "a,b,c".split(",", 1) which gives ['a', 'b,c'].
Padding, Alignment, and Trimming
For formatting output, these methods help align text:
str.center(width, fillchar=' ')– centers the string in a field of given width.str.ljust(width, fillchar=' ')– left-justifies.str.rjust(width, fillchar=' ')– right-justifies.str.zfill(width)– pads with zeros on the left, useful for numbers.str.expandtabs(tabsize=8)– replaces tabs with spaces.
Example: "42".zfill(5) returns "00042". "hi".center(7, '*') returns "**hi***" (note the extra asterisk on the right because of odd width).
Testing String Properties
Python provides methods that return True or False about the string’s content:
str.isalnum()– True if all characters are alphanumeric (letters or digits).str.isalpha()– True if all characters are alphabetic.str.isdigit()– True if all characters are digits (0-9, also superscripts).str.isdecimal()– True if all characters are decimal digits (0-9 only).str.isnumeric()– True if all characters are numeric (includes fractions, Roman numerals).str.isspace()– True if all characters are whitespace.str.isprintable()– True if all characters are printable.
Note the subtle differences: "²".isdigit() is True, but "²".isdecimal() is False. For user input validation, isdecimal() is usually safer for ordinary numbers.
Formatting and Miscellaneous Methods
Beyond the basics, there are methods for advanced formatting and conversion:
str.format(*args, **kwargs)– performs string formatting with placeholders like{}.str.format_map(mapping)– similar but uses a dictionary directly.str.encode(encoding='utf-8', errors='strict')– returns a bytes object.str.join()is actually a method of the separator string, not the list.str.removeprefix(prefix)andstr.removesuffix(suffix)– added in Python 3.9, remove a fixed prefix/suffix if present.str.translate(table)– maps characters using a translation table (often fromstr.maketrans).
Example of removeprefix: "test_123".removeprefix("test_") returns "123". This is cleaner than slicing and avoids errors if the prefix is missing.
Common Pitfalls and Misconceptions
One common mistake is assuming str.split() with no arguments splits on single spaces; actually it splits on any whitespace and discards empty strings. Another is confusing str.find() with str.index()—if the substring is missing, find returns -1, but index raises an exception. Also, remember that strings are immutable: methods like replace do not change the original; you must reassign the result.
Another misconception is that str.isdigit() and str.isnumeric() are identical. They are not: isnumeric() accepts more Unicode characters, such as fractions. For validating integer input, isdecimal() is the most restrictive and usually what you want.
Frequently Asked Questions
What is the difference between find() and index()?
find() returns -1 when the substring is not found, while index() raises a ValueError. Use find() when you expect the substring might be absent and want to handle it gracefully; use index() when you want to fail fast.
How do I split a string by multiple delimiters?
Use the re.split() function from the re module, for example re.split(r'[,;]', "a,b;c") returns ['a', 'b', 'c']. The built-in split() only accepts a single separator string.
Why does "hello".replace("l", "L") not change the original string?
Because strings are immutable in Python. The replace() method returns a new string; you must assign it to a variable if you want to keep the result: s = s.replace("l", "L").
How do I check if a string contains only numbers?
Use str.isdecimal() for ordinary digits (0-9). If you want to allow superscripts or fractions, use str.isdigit() or str.isnumeric(), but be aware of the differences. For example, "²".isdecimal() is False.
What is the fastest way to concatenate many strings?
Use str.join() on a list of strings, e.g., "".join(list_of_strings). It is faster and more memory-efficient than repeated + concatenation in a loop.
Can I use string methods on bytes objects?
No, bytes objects have their own methods (like bytes.decode()), but they are different. To use string methods on bytes, first decode to str using bytes.decode('utf-8').
Related
- Select All Windows Explorer: Steps & Tips
- City 8 Codes for Traffic Signals Explained
- Federal Reserve Balance Sheet Explained Simply
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Excel Heat Map: Apply a Formula to Color CellsTo apply a formula to an Excel heat map, select the cells, choose Home > Conditional Formatting >…
- Excel Table Filter by Text in Another Cell?Yes. To filter an Excel table using text in another cell, add a helper column with a formula…
- Excel Formula Conditional Formatting TextThe fastest way to apply conditional formatting based on text in Excel is to select your data, go…
- Excel GROUPBY With Multiple Criteria: Filter ArraysTo group Excel data while applying multiple row-level criteria, use the filter_array argument in GROUPBY and combine AND…
- What-If Analysis in Excel: How It Works and When to Use ItWhat-If Analysis in Excel is a set of tools for seeing how changing input values affects a formula’s…
- VLOOKUP Examples for Beginners: A Practical Excel GuideIn Excel, VLOOKUP finds a value in the first column of a range and returns related information from…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.