PYnative

Practice Coding

  • Python â–¼
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Coding Exercises â–¼
    • Python Exercises
    • C++ Exercises
    • C Programming Exercises
    • Java Exercises
    • C# Exercises
  • MCQsâ–¼
    • Python MCQ Quizzes
    • Java MCQ Quizzes
    • C++ MCQ Quizzes
  • Compilersâ–¼
    • Online Python Compiler
    • Online C Compiler
    • Online C++ Compiler
    • Online Java Compiler
    • Online C# Compiler
Home » Python » Basics » Python String Methods: Complete List With Examples

Python String Methods: Complete List With Examples

Updated on: December 4, 2026 | Leave a Comment

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
    • casefold() vs. lower()
    • A title() gotcha
  • Removing whitespace and characters
    • removeprefix() and removesuffix()
  • Searching in strings
    • find(), rfind(), index(), and rindex()
    • count()
    • startswith() and endswith()
  • Replacing text
    • translate() and maketrans()
  • Splitting strings
    • split() and rsplit()
    • splitlines()
    • partition() and rpartition()
  • Joining strings
  • Alignment and padding
    • expandtabs()
  • Checking string content (is methods)
    • isdecimal() vs. isdigit() vs. isnumeric()
    • Other 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:

text = "hello world"

print(text.upper())
print(text.title())
print(text)  # unchanged: strings are immutableCode language: Python (python)

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:

raw = "   PYTHON Programming   "
clean = raw.strip().lower().replace(" ", "_")
print(clean)Code language: Python (python)

Output:

python_programming

To see every method from Python itself, run print(dir(str)) or help(str.split).

All Python string methods

MethodDescription
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

text = "pyTHON is FUN"

print(text.upper())
print(text.lower())
print(text.capitalize())
print(text.title())
print(text.swapcase())Code language: Python (python)

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:

a = "Straße"
b = "STRASSE"

print(a.lower() == b.lower())
print(a.casefold() == b.casefold())Code language: Python (python)

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:

import string

print("they're bill's friends".title())
print(string.capwords("they're bill's friends"))Code language: Python (python)

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:

value = "   hello world \n"

print(repr(value.strip()))
print(repr(value.lstrip()))
print(repr(value.rstrip()))Code language: Python (python)

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:

print("xxhelloxx".strip("x"))
print("www.example.com".strip("w.moc"))  # removes any of w . m o c
print("$1,250.00".lstrip("$"))Code language: Python (python)

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:

url = "https://pynative.com"
print(url.removeprefix("https://"))

filename = "report_final.csv"
print(filename.removesuffix(".csv"))
print(filename.removesuffix(".txt"))  # unchangedCode language: Python (python)

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:

text = "Python is easy. Python is powerful."

print(text.find("Python"))
print(text.rfind("Python"))   # last occurrence
print(text.find("Java"))
print(text.find("Python", 5))  # start searching at index 5

try:
    text.index("Java")
except ValueError as error:
    print("Error:", error)Code language: Python (python)

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()

sentence = "the cat sat on the mat with the hat"
print(sentence.count("the"))
print(sentence.count("at"))
print("aaaa".count("aa"))  # non-overlapping matchesCode language: Python (python)

Output:

3
4
2

startswith() and endswith()

Both accept a tuple to check several options at once:

filename = "photo.JPG"

print(filename.startswith("photo"))
print(filename.lower().endswith((".jpg", ".jpeg", ".png")))

url = "https://pynative.com"
print(url.startswith(("http://", "https://")))Code language: Python (python)

Output:

True
True
True

Replacing text

replace(old, new) replaces every occurrence. Pass a third argument to limit the number of replacements:

text = "I like cats. Cats are great. cats!"

print(text.replace("cats", "dogs"))
print(text.replace("cats", "dogs", 1))
print(text.replace(" ", ""))  # remove all spacesCode language: Python (python)

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():

# Replace characters
table = str.maketrans("aeiou", "12345")
print("programming language".translate(table))

# Remove characters (third argument)
table = str.maketrans("", "", "!?.,")
print("Hello, World! How are you?".translate(table))

# Map with a dictionary
table = str.maketrans({"&": "and", "@": "at"})
print("Tom & Jerry @ home".translate(table))Code language: Python (python)

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:

print("  Python   is  fun ".split())
print("a,b,,c".split(","))     # empty strings are kept
print("2026-12-04".split("-"))
print("a b c d".split(" ", 2))  # maxsplit=2
print("a b c d".rsplit(" ", 1))  # split once from the rightCode language: Python (python)

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:

path = "archive.backup.tar.gz"
name, ext = path.rsplit(".", 1)
print(name, ext)Code language: Python (python)

Output:

archive.backup.tar gz

splitlines()

splitlines() splits at line breaks and handles \n, \r\n, and other line endings:

text = "first line\nsecond line\r\nthird line"
print(text.splitlines())
print(text.splitlines(keepends=True))Code language: Python (python)

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:

email = "jessa@example.com"
user, sep, domain = email.partition("@")
print(user, domain)

print("key=value=more".partition("="))
print("key=value=more".rpartition("="))
print("no separator".partition("="))Code language: Python (python)

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:

words = ["Python", "string", "methods"]

print(" ".join(words))
print(", ".join(words))
print("\n".join(words))

numbers = [1, 2, 3]
print("+".join(str(n) for n in numbers), "=", sum(numbers))Code language: Python (python)

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:

print("|" + "left".ljust(10) + "|")
print("|" + "right".rjust(10) + "|")
print("|" + "mid".center(10) + "|")
print("|" + "mid".center(10, "*") + "|")
print("42".zfill(5))
print("-42".zfill(5))  # the sign stays in frontCode language: Python (python)

Output:

|left      |
|     right|
|   mid    |
|***mid****|
00042
-0042

Example: print a simple report

items = [("Coffee", 3.5), ("Sandwich", 7.25), ("Water", 1)]

print("MENU".center(20, "="))
for name, price in items:
    print(name.ljust(12, ".") + f"{price:.2f}".rjust(8))Code language: Python (python)

Output:

========MENU========
Coffee......    3.50
Sandwich....    7.25
Water.......    1.00

expandtabs()

data = "Name\tAge\tCity"
print(data.expandtabs(10))Code language: Python (python)

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().

samples = ["Python", "Python3", "2026", "hello world", "   ", "Hello World", ""]

for s in samples:
    print(f"{s!r:15} alpha={s.isalpha()!s:5} alnum={s.isalnum()!s:5} "
          f"digit={s.isdigit()!s:5} space={s.isspace()!s:5} title={s.istitle()}")Code language: Python (python)

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:

Valueisdecimal()isdigit()isnumeric()
"123"TrueTrueTrue
"²" (superscript two)FalseTrueTrue
"½" (one half)FalseFalseTrue
"-5" or "3.14"FalseFalseFalse
for value in ["123", "²", "½", "-5", "3.14"]:
    print(f"{value!r:7} {value.isdecimal()!s:6} {value.isdigit()!s:6} {value.isnumeric()}")Code language: Python (python)

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

print("HELLO".isupper(), "hello".islower())
print("my_var".isidentifier(), "2var".isidentifier())
print("café".isascii(), "cafe".isascii())
print("tab\there".isprintable())Code language: Python (python)

Output:

True True
True False
False True
False

Formatting methods: format() and format_map()

template = "{name} is {age} years old"
print(template.format(name="Jessa", age=28))

person = {"name": "Kelly", "age": 31}
print(template.format_map(person))Code language: Python (python)

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:

text = "naïve café"
print(text.encode("utf-8"))
print(text.encode("ascii", errors="ignore"))
print(text.encode("ascii", errors="replace"))Code language: Python (python)

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

raw_emails = ["  Jessa@Example.COM ", "KELLY@example.com\n", " emma@EXAMPLE.com"]
emails = [e.strip().lower() for e in raw_emails]
print(emails)Code language: Python (python)

Output:

['jessa@example.com', 'kelly@example.com', 'emma@example.com']

Example 2: Turn a title into a URL slug

title = "  10 Python String Methods You Should Know!  "
allowed = "".join(ch if ch.isalnum() or ch == " " else "" for ch in title.lower())
slug = "-".join(allowed.split())
print(slug)Code language: Python (python)

Output:

10-python-string-methods-you-should-know

Example 3: Mask a credit card number

card = "4111222233334444"
masked = card[-4:].rjust(len(card), "*")
print(masked)Code language: Python (python)

Output:

************4444

Example 4: Parse key-value settings

config_text = """host = localhost
port = 8080
# comment line
debug = true"""

settings = {}
for line in config_text.splitlines():
    line = line.strip()
    if not line or line.startswith("#"):
        continue
    key, _, value = line.partition("=")
    settings[key.strip()] = value.strip()

print(settings)Code language: Python (python)

Output:

{'host': 'localhost', 'port': '8080', 'debug': 'true'}

Common mistakes

  • Not saving the result. name.strip() returns a new string. Write name = name.strip().
  • Using strip("abc") to remove a word. It removes any of the characters a, b, and c from both ends. Use removeprefix() or removesuffix().
  • Calling join() on the list. It’s " ".join(words), not words.join(" ").
  • Joining non-strings. ", ".join([1, 2]) raises a TypeError. Convert with map(str, ...).
  • Using isdigit() to validate numbers. It rejects "-5" and "3.5" and accepts "²", which int() can’t convert.
  • Expecting split(" ") and split() to behave the same. split(" ") keeps empty strings for repeated spaces.
print("a  b".split(" "))
print("a  b".split())Code language: Python (python)

Output:

['a', '', 'b']
['a', 'b']

Practice exercises

Exercise 1: Count the words in a sentence and print the longest word.

sentence = "Python string methods make text processing simple"
words = sentence.split()
print(len(words))
print(max(words, key=len))Code language: Python (python)

Output:

7
processing

Exercise 2: Reverse the order of words in a sentence.

sentence = "learn python the easy way"
print(" ".join(reversed(sentence.split())))Code language: Python (python)

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.

def is_strong(password):
    return (
        len(password) >= 8
        and any(ch.isupper() for ch in password)
        and any(ch.islower() for ch in password)
        and any(ch.isdigit() for ch in password)
    )

for pwd in ["Python2026", "python", "PYTHON2026", "Py2"]:
    print(pwd, is_strong(pwd))Code language: Python (python)

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(), and casefold().
  • Clean text with strip(), lstrip(), rstrip(), removeprefix(), and removesuffix().
  • Search with find(), index(), count(), startswith(), and endswith(). Replace with replace() and translate().
  • Split with split(), rsplit(), splitlines(), and partition(). Join with separator.join(items).
  • Align with ljust(), rjust(), center(), and zfill(). Validate with the is...() methods.

Also, See:

  • Strings in Python: A Complete Guide
  • String Slicing and Indexing in Python
  • Python String Exercises
  • Top 40+ Python String Interview Questions

Filed Under: Python, Python Basics

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Basics

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises
Java Exercises
C# Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Python Python Basics
TweetF  sharein  shareP  Pin

  Python Tutorials

  • Get Started with Python
  • Python Statements
  • Python Comments
  • Python Keywords
  • Python Variables
  • Python Operators
  • Python Data Types
  • Python Casting
  • Python Control Flow statements
  • Python For Loop
  • Python While Loop
  • Python Break and Continue
  • Python Nested Loops
  • Python Input and Output
  • Python range function
  • Check user input is String or Number
  • Accept List as a input from user
  • Python Numbers
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python Functions
  • Python Modules
  • Python isinstance()
  • Python OOP
  • Python Inheritance
  • Python Exceptions
  • Python Exercise for Beginners
  • Python Quiz for Beginners

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

  • Python Basics
  • Python Exercises
  • Python Quizzes
  • Python File Handling
  • Python Date and Time
  • Python OOP
  • Python Random
  • Python Regex
  • Python Pandas
  • Python Databases
  • Python MySQL
  • Python PostgreSQL
  • Python SQLite
  • Python JSON

About PYnative

PYnative.com is a platform built to help developers learn by doing. Solve coding exercises, take MCQs, and run code directly in built-in online compilers.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises
  • Java Exercises
  • C# Exercises

MCQ Quizzes

  • Python MCQs
  • Java MCQs
  • C++ MCQs

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com