Python String Methods

These methods are defined for all instances of the built-in str type.


Methods

Method Name

Description

Example

capitalize

str.capitalize()

casefold

Convert to lowercase

str.casefold()

center

str.center(width, ' ')

count

str.count(sub, 0, len(sub)-1)

encode

str.encode(encoding='utf-8', errors='strict')

endswith

str.endswith(suffix0, len(sub)-1)

expandtabs

str.expandtabs(tabsize=8)

find

str.find(sub, 0, len(sub)-1)

format

str.format(**kwargs)

format_map

str.format_map(kwargs)

index

str.index(sub, 0, len(sub)-1)

isalnum

str.isalnum()

isalpha

str.isalpha()

isascii

str.isascii()

isdecimal

str.isdecimal()

isdigit

str.isdigit()

isidentifier

str.isidentifier()

islower

str.islower()

isnumeric

str.isnumeric()

isprintable

str.isprintable()

isspace

str.isspace()

istitle

str.istitle()

isupper

str.isupper()

join

str.join(iterable)

ljust

str.ljust(width, ' ')

lower

Convert to lowercase

str.lower()

lstrip

str.lstrip(line)

maketrans

partition

str.partition(sep)

removeprefix

str.removeprefix(prefix)

removesuffix

str.removesuffix(suffix)

replace

str.replace(old, new, 1)

rfind

str.rfind(sub, 0, len(sub)-1)

rindex

str.rindex(sub, 0, len(sub)-1)

rjust

str.rjust(width[, fillchar])

rpartition

str.rpartition(sep)

rstrip

str.rstrip(line)

split

str.split(sep=' ', maxsplit=1)

splitlines

str.splitlines()

startswith

str.startswith(prefix, 0, len(sub)-1)

strip

str.strip(line)

swapcase

str.swapcase()

title

str.title()

translate

str.translate(table)

upper

Convert to uppercase

str.upper()

zfill

str.zfill(width)

Casefolding

The upper, lower, and casefold methods are closely related. The major difference is that lower is reversible.

orig = ['ß', 'á', 'Á']
[o.upper() for o in orig]     # ['SS', 'Á', 'Á']

[o.casefold() for o in orig]  # ['ss', 'á', 'á']

[o.lower() for o in orig]     # ['ß', 'á', 'á']


CategoryRicottone

Python/StringMethods (last edited 2025-12-23 04:06:27 by DominicRicottone)