Python offers a wide range of built-in methods for string manipulation.
It is important to note that strings in Python are immutable , meaning they cannot be changed once created. As a result, string methods return a new, modified string instead of altering the original.
I have classified string methods into 5 categories based on their functionality. Click on any method to learn more about it.
(1) Case Conversion Methods
Method Description Example lower()
Converts to lowercase "HELLO".lower()
→ "hello"
upper()
Converts to uppercase "hello".upper()
→ "HELLO"
title()
Capitalizes the first letter of each word "hello world".title()
→ "Hello World"
capitalize()
Capitalizes the first character, lowercases the rest "hello WORLD".capitalize()
→ "Hello world"
casefold()
Converts to lowercase more aggressively "Straße".casefold()
→ "strasse"
swapcase()
Swaps case of each character "Hello".swapcase()
→ "hELLO"
(2) Search and Find Methods
Method Description Example find()
Returns the index of the first occurrence of the substring if found, else returns -1
"hello".find("e")
→ 1
rfind()
Returns the index of the last occurrence of the substring if found, else returns -1
"hello".rfind("l")
→ 3
index()
Similar to find()
, but raises ValueError
if the substring is not found "hello".index("e")
→ 1
rindex()
Similar to rfind()
, but raises ValueError
if the substring is not found. "hello".rindex("l")
→ 3
startswith()
Returns True
if the string starts with the specified prefix "hello".startswith("he")
→ True
endswith()
Returns True
if the string ends with the specified suffix "hello".endswith("lo")
→ True
count()
Returns the number of occurrences of a substring "hello".count("l")
→ 2
(3) String Modification and Replacement Methods
Method Description Example replace()
Replaces all occurrences of a substring with another string "hello".replace("l", "t")
→ "hetto"
strip()
Removes leading and trailing characters (whitespace by default) " hello ".strip()
→ "hello"
lstrip()
Removes leading characters (whitespace by default) "llama".lstrip("l")
→ "ama"
rstrip()
Removes trailing characters (whitespace by default) "buzz".rstrip("z")
→ "bu"
join()
Joins elements of an iterator with the string as a separator "-".join(['a', 'b', 'c'])
→ "a-b-c"
split()
Splits a string into a list using a delimiter (default: whitespace) "a,b,c".split(",")
→ ['a', 'b', 'c']
rsplit()
Like split()
, but splits from the right "a,b,c".rsplit(",", 1)
→ ['a,b', 'c']
splitlines()
Splits a string at line breaks (\n
, \r\n
, etc) "a\nb".splitlines()
→ ['a', 'b']
expandtabs()
Replaces tabs (\t
) with spaces (default: 8 spaces per tab) "a\tb".expandtabs(5)
→ "a b"
encode()
Converts a string into bytes using a specified encoding (default is UTF-8) "hello".encode()
→ b'hello'
maketrans()
Creates a translation map to be used with translate()
str.maketrans("abc", "123")
→ {97: 49, 98: 50, 99: 51}
translate()
Translates characters into a string using a translation map from maketrans()
"abc".translate(str.maketrans("abc", "123"))
→ "123"
partition()
Splits the string at the first occurrence of the separator into a 3-part tuple "a,b,c".partition(',')
→ ('a', ',', 'b,c')
rpartition()
Splits the string at the last occurrence of the separator into a 3-part tuple "a,b,c".rpartition(',')
→ ('a,b', ',', 'c')
(4) String Validation Methods
Method Description Example isalnum()
Returns True
if all characters are alphanumeric (a-z
, A-Z
, and 0-9
) "abc123".isalnum()
→ True
isaplha()
Returns True
if all characters are alphabetic (a-z
and A-Z
) "abc".isalpha()
→ True
isascii()
Returns True
if all characters are ASCII "abc123".isascii()
→ True
isdecimal()
Returns True
if all characters are decimal digits. Stricter than isdigit()
"123".isdecimal()
→ True
isdigit()
Returns True
if all characters are digits "²5".isdigit()
→ True
isnumeric()
Returns True
if all characters are numeric "Ⅷ".isnumeric()
→ True
isidentifier()
Returns True
if the string is a valid Python identifier "user_age".isidentifier()
→ True
islower()
Returns True
if all characters are lowercase "abc".islower()
→ True
isupper()
Returns True
if all characters are uppercase "ABC".isupper()
→ True
istitle()
Returns True
if the string follows title case (first letter of each word uppercase) "Hello World".istitle()
→ True
isspace()
Returns True
if all characters are whitespace "\n\t".isspace()
→ True
isprintable()
Returns True
if all characters are printable "abc\n".isprintable()
→ False
startswith()
Returns True
if the string starts with a given substring "hello".startswith("he")
→ True
endswith()
Returns True
if the string ends with a given substring "hello".endswith("lo")
→ True
(5) Alignment, Padding, and Formatting Methods
Method Description Example ljust()
Left-justifies the string with padding (default: space) "hi".ljust(5, '-')
→ "hi---"
rjust()
Right-justifies the string with padding (default: space) "hi".rjust(5, '-')
→ "---hi"
center()
Centers the string with padding (default: space) "hi".center(5, '-')
→ "--hi-"
zfill()
Pads the string with leading zeros to reach a specified width "9".zfill(3)
→ "009"
format()
Formats string with placeholders and values "Name: {}".format("James")
→ "Name: James"
format_map()
Formats using a dictionary (mapping) of values "age: {age}".format_map({"age": 32})
→ "age: 32"