Python strings come with 47 built-in methods for the jobs you do with text every day: changing case, removing spaces, searching, replacing, splitting a sentence into words, joining words back together, and checking whether input contains only digits or letters.
This tutorial lists every string method in one table, then explains them by task with runnable examples, so you can quickly find the one you need.
Key terms used in this article:
- Method: A function that belongs to an object. You call it with a dot:
text.upper(). - Immutable: Strings can’t be changed in place. Every string method returns a new string (or another value) and leaves the original unchanged.
- Whitespace: Spaces, tabs (
\t), and newlines (\n). - Substring: A smaller string inside a bigger string, such as
"cat"in"concatenate".
Table of contents
- How string methods work
- All Python string methods
- Case conversion methods
- Removing whitespace and characters
- Searching in strings
- Replacing text
- Splitting strings
- Joining strings
- Alignment and padding
- Checking string content (is methods)
- Formatting methods: format() and format_map()
- encode()
- Real-world examples
- Common mistakes
- Practice exercises
- Summary
How string methods work
Call a method by writing the string (or a variable), a dot, the method name, and parentheses:
Output:
HELLO WORLD Hello World hello world
Because methods return new strings, you must assign the result if you want to keep it, and you can chain several methods in one line:
Output:
python_programming
To see every method from Python itself, run print(dir(str)) or help(str.split).
All Python string methods
| Method | Description |
|---|---|
capitalize() | Uppercases the first character and lowercases the rest |
casefold() | Returns an aggressive lowercase version for case-insensitive comparisons |
center(width, fillchar) | Centers the string in a field of the given width |
count(sub, start, end) | Counts non-overlapping occurrences of a substring |
encode(encoding, errors) | Encodes the string into bytes |
endswith(suffix, start, end) | Returns True if the string ends with the suffix |
expandtabs(tabsize) | Replaces tab characters with spaces |
find(sub, start, end) | Returns the lowest index of a substring, or -1 if not found |
format(*args, **kwargs) | Formats the string using replacement fields |
format_map(mapping) | Formats the string using values from a mapping |
index(sub, start, end) | Like find(), but raises ValueError if not found |
isalnum() | True if all characters are letters or digits |
isalpha() | True if all characters are letters |
isascii() | True if all characters are ASCII (or the string is empty) |
isdecimal() | True if all characters are decimal digits (0-9 and other scripts’ digits) |
isdigit() | True if all characters are digits, including superscripts |
isidentifier() | True if the string is a valid Python identifier |
islower() | True if all cased characters are lowercase |
isnumeric() | True if all characters are numeric, including fractions and Roman numerals |
isprintable() | True if all characters are printable (or the string is empty) |
isspace() | True if all characters are whitespace |
istitle() | True if the string is in title case |
isupper() | True if all cased characters are uppercase |
join(iterable) | Joins strings from an iterable, using the string as a separator |
ljust(width, fillchar) | Left-aligns the string in a field of the given width |
lower() | Converts all characters to lowercase |
lstrip(chars) | Removes leading characters (whitespace by default) |
maketrans(x, y, z) | Creates a translation table for translate() |
partition(sep) | Splits at the first separator into a 3-item tuple |
removeprefix(prefix) | Removes a prefix if present (Python 3.9+) |
removesuffix(suffix) | Removes a suffix if present (Python 3.9+) |
replace(old, new, count) | Replaces occurrences of a substring |
rfind(sub, start, end) | Returns the highest index of a substring, or -1 |
rindex(sub, start, end) | Like rfind(), but raises ValueError if not found |
rjust(width, fillchar) | Right-aligns the string in a field of the given width |
rpartition(sep) | Splits at the last separator into a 3-item tuple |
rsplit(sep, maxsplit) | Splits from the right |
rstrip(chars) | Removes trailing characters (whitespace by default) |
split(sep, maxsplit) | Splits the string into a list |
splitlines(keepends) | Splits the string at line boundaries |
startswith(prefix, start, end) | Returns True if the string starts with the prefix |
strip(chars) | Removes leading and trailing characters (whitespace by default) |
swapcase() | Swaps uppercase and lowercase |
title() | Uppercases the first letter of each word |
translate(table) | Replaces or deletes characters using a translation table |
upper() | Converts all characters to uppercase |
zfill(width) | Pads the string on the left with zeros |
Case conversion methods
Output:
PYTHON IS FUN python is fun Python is fun Python Is Fun PYthon IS fun
casefold() vs. lower()
casefold() is a stronger version of lower() designed for comparing text from any language. For example, the German letter ß is equivalent to ss:
Output:
False True
Use casefold() for case-insensitive comparisons, and lower() when you just want lowercase text to display.
A title() gotcha
title() treats any non-letter as a word boundary, so apostrophes produce odd results. Use string.capwords() when that matters:
Output:
They'Re Bill'S Friends They're Bill's Friends
Removing whitespace and characters
strip(), lstrip(), and rstrip() remove characters from the ends of a string. Without an argument, they remove whitespace:
Output:
'hello world' 'hello world \n' ' hello world'
When you pass a string, it’s treated as a set of characters to remove, not as a prefix or suffix:
Output:
hello example 1,250.00
removeprefix() and removesuffix()
To remove an exact prefix or suffix, use removeprefix() and removesuffix() (Python 3.9+). They remove the text only if it’s present:
Output:
pynative.com report_final report_final.csv
Searching in strings
find(), rfind(), index(), and rindex()
find() returns the index of the first match or -1 if there’s none. index() does the same but raises a ValueError:
Output:
0 16 -1 16 Error: substring not found
Use find() when “not found” is a normal outcome. Use index() when a missing substring is a bug. If you only need to know whether a substring exists, in is simpler: "Python" in text.
count()
Output:
3 4 2
startswith() and endswith()
Both accept a tuple to check several options at once:
Output:
True True True
Replacing text
replace(old, new) replaces every occurrence. Pass a third argument to limit the number of replacements:
Output:
I like dogs. Cats are great. dogs! I like dogs. Cats are great. cats! Ilikecats.Catsaregreat.cats!
replace() is case-sensitive, which is why Cats wasn’t replaced. Use the re module’s re.sub() with re.IGNORECASE for case-insensitive replacements.
translate() and maketrans()
translate() replaces or removes many single characters in one pass. Build the translation table with str.maketrans():
Output:
pr4gr1mm3ng l1ng51g2 Hello World How are you Tom and Jerry at home
Splitting strings
split() and rsplit()
split() without arguments splits on any run of whitespace and ignores leading and trailing spaces. With a separator, it splits exactly at that separator:
Output:
['Python', 'is', 'fun'] ['a', 'b', '', 'c'] ['2026', '12', '04'] ['a', 'b', 'c d'] ['a b c', 'd']
rsplit() is handy when you need the last part, such as a file extension:
Output:
archive.backup.tar gz
splitlines()
splitlines() splits at line breaks and handles \n, \r\n, and other line endings:
Output:
['first line', 'second line', 'third line'] ['first line\n', 'second line\r\n', 'third line']
partition() and rpartition()
partition() splits at the first separator and always returns a 3-item tuple: the part before, the separator, and the part after:
Output:
jessa example.com
('key', '=', 'value=more')
('key=value', '=', 'more')
('no separator', '', '')
Joining strings
join() is called on the separator, and takes an iterable of strings:
Output:
Python string methods Python, string, methods Python string methods 1+2+3 = 6
join() is the fastest way to build a string from many pieces.
Alignment and padding
ljust(), rjust(), and center() pad a string to a given width. zfill() pads numbers with zeros:
Output:
|left | | right| | mid | |***mid****| 00042 -0042
Example: print a simple report
Output:
========MENU======== Coffee...... 3.50 Sandwich.... 7.25 Water....... 1.00
expandtabs()
Output:
Name Age City
Checking string content (is methods)
The is...() methods return True or False. They return False for an empty string, except isascii() and isprintable().
Output:
'Python' alpha=True alnum=True digit=False space=False title=True 'Python3' alpha=False alnum=True digit=False space=False title=True '2026' alpha=False alnum=True digit=True space=False title=False 'hello world' alpha=False alnum=False digit=False space=False title=False ' ' alpha=False alnum=False digit=False space=True title=False 'Hello World' alpha=False alnum=False digit=False space=False title=True '' alpha=False alnum=False digit=False space=False title=False
isdecimal() vs. isdigit() vs. isnumeric()
The three digit checks differ for special characters. For validating user input that you’ll pass to int(), isdecimal() is the safest:
| Value | isdecimal() | isdigit() | isnumeric() |
|---|---|---|---|
"123" | True | True | True |
"²" (superscript two) | False | True | True |
"½" (one half) | False | False | True |
"-5" or "3.14" | False | False | False |
Output:
'123' True True True '²' False True True '½' False False True '-5' False False False '3.14' False False False
None of them accept a minus sign or a decimal point. To check for any number, try converting with float() inside try/except.
Other is methods
Output:
True True True False False True False
Formatting methods: format() and format_map()
Output:
Jessa is 28 years old Kelly is 31 years old
For most code, f-strings are clearer. See Python f-Strings and String Formatting.
encode()
encode() converts a string into bytes, which you need for files, networks, and hashing:
Output:
b'na\xc3\xafve caf\xc3\xa9' b'nave caf' b'na?ve caf?'
Real-world examples
Example 1: Clean and normalize user input
Output:
['jessa@example.com', 'kelly@example.com', 'emma@example.com']
Example 2: Turn a title into a URL slug
Output:
10-python-string-methods-you-should-know
Example 3: Mask a credit card number
Output:
************4444
Example 4: Parse key-value settings
Output:
{'host': 'localhost', 'port': '8080', 'debug': 'true'}
Common mistakes
- Not saving the result.
name.strip()returns a new string. Writename = name.strip(). - Using
strip("abc")to remove a word. It removes any of the charactersa,b, andcfrom both ends. Useremoveprefix()orremovesuffix(). - Calling
join()on the list. It’s" ".join(words), notwords.join(" "). - Joining non-strings.
", ".join([1, 2])raises aTypeError. Convert withmap(str, ...). - Using
isdigit()to validate numbers. It rejects"-5"and"3.5"and accepts"²", whichint()can’t convert. - Expecting
split(" ")andsplit()to behave the same.split(" ")keeps empty strings for repeated spaces.
Output:
['a', '', 'b'] ['a', 'b']
Practice exercises
Exercise 1: Count the words in a sentence and print the longest word.
Output:
7 processing
Exercise 2: Reverse the order of words in a sentence.
Output:
way easy the python learn
Exercise 3: Check whether a password has at least 8 characters, one uppercase letter, one lowercase letter, and one digit.
Output:
Python2026 True python False PYTHON2026 False Py2 False
Summary
- Python strings have 47 methods. All of them return new values and leave the original string unchanged.
- Change case with
upper(),lower(),title(),capitalize(),swapcase(), andcasefold(). - Clean text with
strip(),lstrip(),rstrip(),removeprefix(), andremovesuffix(). - Search with
find(),index(),count(),startswith(), andendswith(). Replace withreplace()andtranslate(). - Split with
split(),rsplit(),splitlines(), andpartition(). Join withseparator.join(items). - Align with
ljust(),rjust(),center(), andzfill(). Validate with theis...()methods.
Also, See:

Leave a Reply