String Methods

Complete reference of all Python string methods with syntax and examples

8 sections42 methods

upper()

string.upper()
str

Converts all characters to uppercase

Example
text = "hello world"
result = text.upper()
print(result)  # HELLO WORLD

lower()

string.lower()
str

Converts all characters to lowercase

Example
text = "HELLO WORLD"
result = text.lower()
print(result)  # hello world

capitalize()

string.capitalize()
str

Capitalizes the first character and lowercases the rest

Example
text = "hello world"
result = text.capitalize()
print(result)  # Hello world

title()

string.title()
str

Converts the first character of each word to uppercase

Example
text = "hello world"
result = text.title()
print(result)  # Hello World

swapcase()

string.swapcase()
str

Swaps uppercase to lowercase and vice versa

Example
text = "Hello World"
result = text.swapcase()
print(result)  # hELLO wORLD

casefold()

string.casefold()
str

Converts string to lowercase (more aggressive than lower())

Example
text = "HELLO"
result = text.casefold()
print(result)  # hello

find()

string.find(substring, start, end)
int

Returns the lowest index of substring, or -1 if not found

Parameters:

substring (required), start (optional), end (optional)

Example
text = "Hello World"
index = text.find("World")
print(index)  # 6

not_found = text.find("Python")
print(not_found)  # -1

rfind()

string.rfind(substring, start, end)
int

Returns the highest index of substring, or -1 if not found

Parameters:

substring (required), start (optional), end (optional)

Example
text = "Hello World World"
index = text.rfind("World")
print(index)  # 12

index()

string.index(substring, start, end)
int

Like find() but raises ValueError if not found

Parameters:

substring (required), start (optional), end (optional)

Example
text = "Hello World"
index = text.index("World")
print(index)  # 6

rindex()

string.rindex(substring, start, end)
int

Like rfind() but raises ValueError if not found

Parameters:

substring (required), start (optional), end (optional)

Example
text = "Hello World World"
index = text.rindex("World")
print(index)  # 12

count()

string.count(substring, start, end)
int

Returns the number of occurrences of substring

Parameters:

substring (required), start (optional), end (optional)

Example
text = "Hello World World"
count = text.count("World")
print(count)  # 2

startswith()

string.startswith(prefix, start, end)
bool

Returns True if string starts with the specified prefix

Parameters:

prefix (required), start (optional), end (optional)

Example
text = "Hello World"
result = text.startswith("Hello")
print(result)  # True

endswith()

string.endswith(suffix, start, end)
bool

Returns True if string ends with the specified suffix

Parameters:

suffix (required), start (optional), end (optional)

Example
text = "Hello World"
result = text.endswith("World")
print(result)  # True

isalpha()

string.isalpha()
bool

Returns True if all characters are alphabetic

Example
text1 = "Hello"
print(text1.isalpha())  # True

text2 = "Hello123"
print(text2.isalpha())  # False

isdigit()

string.isdigit()
bool

Returns True if all characters are digits

Example
text1 = "12345"
print(text1.isdigit())  # True

text2 = "123abc"
print(text2.isdigit())  # False

isalnum()

string.isalnum()
bool

Returns True if all characters are alphanumeric

Example
text1 = "Hello123"
print(text1.isalnum())  # True

text2 = "Hello 123"
print(text2.isalnum())  # False

isspace()

string.isspace()
bool

Returns True if all characters are whitespace

Example
text1 = "   "
print(text1.isspace())  # True

text2 = " a "
print(text2.isspace())  # False

islower()

string.islower()
bool

Returns True if all cased characters are lowercase

Example
text1 = "hello"
print(text1.islower())  # True

text2 = "Hello"
print(text2.islower())  # False

isupper()

string.isupper()
bool

Returns True if all cased characters are uppercase

Example
text1 = "HELLO"
print(text1.isupper())  # True

text2 = "Hello"
print(text2.isupper())  # False

istitle()

string.istitle()
bool

Returns True if string is titlecased

Example
text1 = "Hello World"
print(text1.istitle())  # True

text2 = "Hello world"
print(text2.istitle())  # False

split()

string.split(separator, maxsplit)
list

Splits string into a list using separator

Parameters:

separator (optional, default: whitespace), maxsplit (optional)

Example
text = "Hello World Python"
words = text.split()
print(words)  # ['Hello', 'World', 'Python']

csv = "apple,banana,orange"
fruits = csv.split(",")
print(fruits)  # ['apple', 'banana', 'orange']

rsplit()

string.rsplit(separator, maxsplit)
list

Splits string from the right

Parameters:

separator (optional), maxsplit (optional)

Example
text = "apple,banana,orange"
result = text.rsplit(",", 1)
print(result)  # ['apple,banana', 'orange']

splitlines()

string.splitlines(keepends)
list

Splits string at line breaks

Parameters:

keepends (optional, default: False)

Example
text = "Hello\nWorld\nPython"
lines = text.splitlines()
print(lines)  # ['Hello', 'World', 'Python']

join()

separator.join(iterable)
str

Joins elements of an iterable with separator

Parameters:

iterable (required)

Example
words = ["Hello", "World", "Python"]
result = " ".join(words)
print(result)  # Hello World Python

result2 = "-".join(words)
print(result2)  # Hello-World-Python

partition()

string.partition(separator)
tuple

Splits string into 3-tuple: (before, separator, after)

Parameters:

separator (required)

Example
text = "Hello-World"
result = text.partition("-")
print(result)  # ('Hello', '-', 'World')

rpartition()

string.rpartition(separator)
tuple

Like partition() but searches from the right

Parameters:

separator (required)

Example
text = "Hello-World-Python"
result = text.rpartition("-")
print(result)  # ('Hello-World', '-', 'Python')

strip()

string.strip(chars)
str

Removes leading and trailing characters (default: whitespace)

Parameters:

chars (optional)

Example
text = "  Hello World  "
result = text.strip()
print(result)  # "Hello World"

text2 = "***Hello***"
result2 = text2.strip("*")
print(result2)  # "Hello"

lstrip()

string.lstrip(chars)
str

Removes leading characters (default: whitespace)

Parameters:

chars (optional)

Example
text = "  Hello World"
result = text.lstrip()
print(result)  # "Hello World"

rstrip()

string.rstrip(chars)
str

Removes trailing characters (default: whitespace)

Parameters:

chars (optional)

Example
text = "Hello World  "
result = text.rstrip()
print(result)  # "Hello World"

removeprefix()

string.removeprefix(prefix)
str

Removes prefix if present (Python 3.9+)

Parameters:

prefix (required)

Example
text = "HelloWorld"
result = text.removeprefix("Hello")
print(result)  # "World"

removesuffix()

string.removesuffix(suffix)
str

Removes suffix if present (Python 3.9+)

Parameters:

suffix (required)

Example
text = "HelloWorld"
result = text.removesuffix("World")
print(result)  # "Hello"

replace()

string.replace(old, new, count)
str

Replaces occurrences of old with new

Parameters:

old (required), new (required), count (optional)

Example
text = "Hello World World"
result = text.replace("World", "Python")
print(result)  # Hello Python Python

result2 = text.replace("World", "Python", 1)
print(result2)  # Hello Python World

translate()

string.translate(table)
str

Translates string using translation table

Parameters:

table (required)

Example
table = str.maketrans("aeiou", "12345")
text = "hello world"
result = text.translate(table)
print(result)  # h2ll4 w4rld

maketrans()

str.maketrans(x, y, z)
dict

Creates a translation table

Parameters:

x (required), y (optional), z (optional)

Example
table = str.maketrans("abc", "123")
text = "abcdef"
result = text.translate(table)
print(result)  # 123def

center()

string.center(width, fillchar)
str

Centers string in a field of given width

Parameters:

width (required), fillchar (optional, default: space)

Example
text = "Hello"
result = text.center(11)
print(result)  # "   Hello   "

result2 = text.center(11, "*")
print(result2)  # "***Hello***"

ljust()

string.ljust(width, fillchar)
str

Left-aligns string in a field of given width

Parameters:

width (required), fillchar (optional)

Example
text = "Hello"
result = text.ljust(10)
print(result)  # "Hello     "

rjust()

string.rjust(width, fillchar)
str

Right-aligns string in a field of given width

Parameters:

width (required), fillchar (optional)

Example
text = "Hello"
result = text.rjust(10)
print(result)  # "     Hello"

zfill()

string.zfill(width)
str

Pads string with zeros on the left

Parameters:

width (required)

Example
number = "42"
result = number.zfill(5)
print(result)  # "00042"

format()

string.format(*args, **kwargs)
str

Formats string using placeholders

Parameters:

*args, **kwargs

Example
template = "Hello {}, you are {} years old"
result = template.format("Alice", 25)
print(result)  # Hello Alice, you are 25 years old

template2 = "Hello {name}, age: {age}"
result2 = template2.format(name="Bob", age=30)
print(result2)  # Hello Bob, age: 30

format_map()

string.format_map(mapping)
str

Formats string using a dictionary

Parameters:

mapping (required)

Example
template = "Hello {name}, age: {age}"
data = {"name": "Alice", "age": 25}
result = template.format_map(data)
print(result)  # Hello Alice, age: 25

encode()

string.encode(encoding, errors)
bytes

Encodes string to bytes

Parameters:

encoding (optional, default: 'utf-8'), errors (optional)

Example
text = "Hello World"
encoded = text.encode()
print(encoded)  # b'Hello World'

encoded_utf16 = text.encode('utf-16')
print(encoded_utf16)

expandtabs()

string.expandtabs(tabsize)
str

Expands tabs to spaces

Parameters:

tabsize (optional, default: 8)

Example
text = "Hello\tWorld"
result = text.expandtabs(4)
print(result)  # "Hello   World"