Python string methods are built-in operations available on objects of the str class. You can use them to change letter case, search or replace text, split and join values, remove whitespace, align output, format values, encode Unicode text, and validate the characters in a string.

Most Python string methods return a new value instead of changing the original string. This is because Python strings are immutable. The complete reference below groups the commonly used methods by purpose and links to detailed tutorials where available.

How Python String Methods Work

A string method is called by writing the string value or variable, followed by a dot, the method name, and parentheses.

</>
Copy
result = string.method(arguments)

For example, the following code removes surrounding whitespace and converts the remaining text to uppercase.

</>
Copy
message = "  Python String Methods  "
result = message.strip().upper()

print(result)
print(message)
PYTHON STRING METHODS
  Python String Methods  

The value stored in message remains unchanged. Both strip() and upper() return new strings.

Python String Methods by Category

The following groups make it easier to choose a method for a particular text-processing task.

String taskRelevant Python methods
Change letter casecapitalize(), casefold(), lower(), swapcase(), title(), upper()
Search and count textcount(), find(), index(), rfind(), rindex(), startswith(), endswith()
Split and combine stringsjoin(), partition(), rpartition(), split(), rsplit(), splitlines()
Remove or replace textreplace(), removeprefix(), removesuffix(), strip(), lstrip(), rstrip(), translate()
Validate string contentsisalnum(), isalpha(), isascii(), isdecimal(), isdigit(), isidentifier(), islower(), isnumeric(), isprintable(), isspace(), istitle(), isupper()
Align and pad textcenter(), expandtabs(), ljust(), rjust(), zfill()
Format or encode textencode(), format(), format_map()

Python String Method Tutorials

  • capitalize()Returns a copy with the first character converted to title case and the remaining characters converted to lowercase.
  • casefold()Returns a case-folded copy suitable for caseless comparisons, including many Unicode characters.
  • center()Returns the string centered within a field of the specified width.
  • count()Returns the number of non-overlapping occurrences of a substring.
  • encode()Encodes the string using the specified character encoding and returns a bytes object.
  • endswith()Returns True when the string ends with the specified suffix.
  • expandtabs()Returns a copy in which tab characters are replaced according to the specified tab size.
  • find()Returns the lowest index of a substring, or -1 when the substring is not found.
  • format()Substitutes values into replacement fields contained in the string.
  • format_map()Formats replacement fields using values supplied by a mapping object.
  • index()Returns the lowest index of a substring and raises ValueError when it is not found.
  • isascii()Returns True when the string is empty or every character is an ASCII character.
  • isalnum()Returns True when the string contains at least one character and every character is alphabetic or numeric.
  • isalpha()Returns True when the string contains at least one character and every character is alphabetic.
  • isdecimal()Returns True when the string contains at least one character and every character is a decimal character.
  • isdigit()Returns True when the string contains at least one character and every character is a digit.
  • isidentifier()Returns True when the string is a syntactically valid Python identifier.
  • islower()Returns True when all cased characters are lowercase and the string contains at least one cased character.
  • isnumeric()Returns True when the string contains at least one character and every character is numeric.
  • isprintable()Returns True when the string is empty or all its characters are printable.
  • isspace()Returns True when the string contains at least one character and every character is whitespace.
  • istitle()Returns True when the cased words in the string follow title-case rules.
  • isupper()Returns True when all cased characters are uppercase and the string contains at least one cased character.
  • join()Returns one string by placing the calling string between the string elements of an iterable.
  • ljust()Returns the string left-aligned within a field of the specified width.
  • lower()Returns a copy with all cased characters converted to lowercase.
  • lstrip()Returns a copy with leading whitespace or specified characters removed.
  • maketrans()Creates a translation table for use with the translate() method.
  • partition()Splits at the first occurrence of a separator and returns a three-item tuple.
  • removeprefix()Returns a copy with the specified prefix removed when the string starts with that prefix.
  • removesuffix()Returns a copy with the specified suffix removed when the string ends with that suffix.
  • replace()Returns a copy in which occurrences of one substring are replaced with another substring.
  • rfind()Returns the highest index of a substring, or -1 when the substring is not found.
  • rindex()Returns the highest index of a substring and raises ValueError when it is not found.
  • rjust()Returns the string right-aligned within a field of the specified width.
  • rpartition()Splits at the last occurrence of a separator and returns a three-item tuple.
  • rsplit()Splits the string from the right and returns a list of substrings.
  • rstrip()Returns a copy with trailing whitespace or specified characters removed.
  • split()Splits the string at a separator and returns a list of substrings.
  • splitlines()Splits the string at line boundaries and returns a list of lines.
  • startswith()Returns True when the string starts with the specified prefix.
  • strip()Returns a copy with leading and trailing whitespace or specified characters removed.
  • swapcase()Returns a copy with uppercase characters converted to lowercase and lowercase characters converted to uppercase.
  • title()Returns a title-cased copy in which words begin with uppercase characters.
  • translate()Returns a copy in which characters are mapped or removed using a translation table.
  • upper()Returns a copy with all cased characters converted to uppercase.
  • zfill()Returns the string padded on the left with zeros until it reaches the specified width.

Python String Case-Conversion Methods

Use case-conversion methods when normalizing input, preparing labels, or comparing text. The appropriate method depends on the intended result.

</>
Copy
text = "pYTHON string METHODS"

print(text.capitalize())
print(text.lower())
print(text.upper())
print(text.title())
print(text.swapcase())
Python string methods
python string methods
PYTHON STRING METHODS
Python String Methods
Python STRING methods

For case-insensitive comparisons involving Unicode text, casefold() is generally more aggressive than lower().

Searching for Substrings with find(), index(), count(), and Prefix Checks

Python provides several methods for locating text. The main difference between find() and index() is their behavior when no match exists: find() returns -1, whereas index() raises a ValueError.

</>
Copy
text = "python string methods"

print(text.find("string"))
print(text.count("t"))
print(text.startswith("python"))
print(text.endswith("methods"))
print(text.find("java"))
7
3
True
True
-1

Splitting and Joining Python Strings

Use split() when converting delimited text into a list. Use join() for the reverse operation: combining an iterable of strings into one string with a selected separator.

</>
Copy
record = "Alice,Developer,New York"
fields = record.split(",")

print(fields)
print(" | ".join(fields))
['Alice', 'Developer', 'New York']
Alice | Developer | New York

Every element passed to join() must be a string. Convert numbers or other object types before joining them.

</>
Copy
numbers = [10, 20, 30]
result = ", ".join(str(number) for number in numbers)

print(result)
10, 20, 30

Removing Whitespace, Prefixes, and Suffixes from Python Strings

The methods strip(), lstrip(), and rstrip() remove whitespace by default. When a character argument is supplied, these methods remove any matching characters from the corresponding ends; they do not remove an exact substring.

</>
Copy
value = "  report.csv  "

print(value.strip())
print(value.lstrip())
print(value.rstrip())
report.csv
report.csv  
  report.csv

Use removeprefix() or removesuffix() when you need to remove one exact prefix or suffix.

</>
Copy
filename = "draft-report.csv"

print(filename.removeprefix("draft-"))
print(filename.removesuffix(".csv"))
report.csv
draft-report

Validating Python String Contents

Methods beginning with is return Boolean values. They are useful for validating identifiers, numbers, alphabetic input, whitespace, and letter case.

</>
Copy
samples = ["Python3", "Python", "123", "12.5", "   "]

for value in samples:
    print(
        repr(value),
        value.isalnum(),
        value.isalpha(),
        value.isdigit(),
        value.isspace()
    )
'Python3' True False False False
'Python' True True False False
'123' True False True False
'12.5' False False False False
'   ' False False False True

A validation method normally returns False for an empty string because there are no characters to validate. isascii() and isprintable() are notable exceptions: both return True for an empty string.

Difference Between isdecimal(), isdigit(), and isnumeric()

These three methods overlap, but they do not recognize exactly the same Unicode characters.

  • isdecimal() is the strictest and recognizes decimal characters suitable for base-10 number notation.
  • isdigit() includes decimal characters and some additional digit characters, such as superscript digits.
  • isnumeric() is the broadest and includes additional numeric characters, such as some fractions and numeral symbols.
</>
Copy
values = ["123", "²", "⅕"]

for value in values:
    print(
        repr(value),
        value.isdecimal(),
        value.isdigit(),
        value.isnumeric()
    )
'123' True True True
'²' False True True
'⅕' False False True

Formatting and Aligning Python Strings

The format() and format_map() methods insert values into replacement fields. Alignment methods such as center(), ljust(), and rjust() help prepare fixed-width text output.

</>
Copy
template = "Name: {name}, Score: {score}"
data = {"name": "Maya", "score": 92}

print(template.format_map(data))
print("Python".center(12, "-"))
print("42".zfill(5))
Name: Maya, Score: 92
---Python---
00042

Encoding a Python String as Bytes

The encode() method converts a Unicode string into a bytes object. UTF-8 is the default encoding.

</>
Copy
text = "café"
encoded = text.encode("utf-8")

print(encoded)
print(type(encoded))
b'caf\xc3\xa9'
<class 'bytes'>

Common Python String Method Mistakes

  • Expecting in-place changes: Assign or otherwise use the returned value because string methods do not modify the original string.
  • Using strip() for an exact prefix: The argument to strip() is treated as a set of characters. Use removeprefix() or removesuffix() for an exact substring.
  • Using index() without handling a missing value: Choose find() when -1 is easier to handle than an exception.
  • Passing non-string values to join(): Convert each item to str before joining.
  • Treating isdigit() as a complete number parser: It does not recognize signs, decimal points, or exponent notation. Use numeric conversion with exception handling when parsing complete numbers.
  • Using title() for every name or heading: Its word-boundary rules may produce unsuitable capitalization for apostrophes, abbreviations, or brand names.

Python String Methods QA Checklist

  • Verify whether the selected method returns a string, Boolean, integer, tuple, list, translation table, or bytes object.
  • Confirm that the returned value is assigned or used when a transformed string is required.
  • Check whether a search method should return -1 or raise ValueError when no match exists.
  • Test validation methods with an empty string and with relevant Unicode characters.
  • Use removeprefix() and removesuffix() for exact boundary text rather than treating strip() as substring removal.
  • Verify the separator direction when using split(), rsplit(), partition(), or rpartition().
  • Ensure every value supplied to join() is already a string.
  • Test encoding and decoding with the same character encoding when converting between str and bytes.

Frequently Asked Questions About Python String Methods

Do Python string methods change the original string?

No. Python strings are immutable. Methods that transform text return a new string, so the result must be assigned to a variable or used directly.

What is the difference between find() and index() in Python?

Both return the position of a matching substring. If no match exists, find() returns -1, while index() raises ValueError.

What is the difference between lower() and casefold()?

lower() performs standard lowercase conversion. casefold() performs a stronger Unicode-aware normalization intended for caseless text comparisons.

Why does join() raise a TypeError for a list of numbers?

join() requires every iterable element to be a string. Convert numeric values first, for example with a generator expression such as ", ".join(str(value) for value in numbers).

Should strip() be used to remove a filename extension?

No. strip() removes matching characters from the ends rather than one exact substring. Use removesuffix(".csv") when an exact suffix should be removed.

Summary of Python String Methods

Python’s str methods cover common text-processing requirements, including case conversion, searching, replacement, validation, splitting, joining, formatting, alignment, trimming, translation, and encoding. Choose a method according to its return type and missing-value behavior, and remember that transformations return new strings rather than modifying existing ones.

Continue with the linked method tutorials above or return to the main Python Tutorial for related Python concepts and examples.