Python provides a rich set of string methods that allow developers to manipulate and analyze text data easily. These methods return new strings or values and do not modify the original string (since strings are immutable).
Here is a complete list of Python string methods along with at least one example for each.
String Case and Format Methods
capitalize()
Capitalizes the first character of a string.
print("hello world".capitalize()) # Output: 'Hello world'
casefold()
Converts string to lowercase, more aggressive than lower()
.
print("HELLO".casefold()) # Output: 'hello'
lower()
Converts string to lowercase.
print("Hello".lower()) # Output: 'hello'
upper()
Converts string to uppercase.
print("hello".upper()) # Output: 'HELLO'
title()
Capitalizes the first letter of each word.
print("hello world".title()) # Output: 'Hello World'
swapcase()
Swaps the case of characters.
print("Hello".swapcase()) # Output: 'hELLO'
Searching and Checking
find()
Returns the index of the first occurrence.
print("hello world".find("world")) # Output: 6
rfind()
Returns the last occurrence index.
print("hello world world".rfind("world")) # Output: 12
index()
Like find()
but raises an error if not found.
print("hello".index("e")) # Output: 1
rindex()
Like rfind()
but raises an error if not found.
print("hello hello".rindex("l")) # Output: 9
startswith()
Checks if string starts with specified value.
print("hello".startswith("he")) # Output: True
endswith()
Checks if string ends with specified value.
print("hello".endswith("lo")) # Output: True
String Testing Methods
isalnum()
Returns True if all characters are alphanumeric.
print("abc123".isalnum()) # Output: True
isalpha()
True if all characters are alphabetic.
print("abc".isalpha()) # Output: True
isdigit()
True if all characters are digits.
print("123".isdigit()) # Output: True
isdecimal()
True if all characters are decimal.
print("123".isdecimal()) # Output: True
isnumeric()
True if all characters are numeric.
print("123".isnumeric()) # Output: True
islower()
True if all characters are lowercase.
print("hello".islower()) # Output: True
isupper()
True if all characters are uppercase.
print("HELLO".isupper()) # Output: True
istitle()
True if string is titlecased.
print("Hello World".istitle()) # Output: True
isspace()
True if all characters are whitespace.
print(" ".isspace()) # Output: True
Modifying Strings
replace()
Replaces a substring with another.
print("hello world".replace("world", "Python")) # Output: 'hello Python'
strip()
Removes whitespace from both ends.
print(" hello ".strip()) # Output: 'hello'
lstrip()
Removes leading whitespace.
print(" hello".lstrip()) # Output: 'hello'
rstrip()
Removes trailing whitespace.
print("hello ".rstrip()) # Output: 'hello'
split()
Splits string into a list.
print("a,b,c".split(",")) # Output: ['a', 'b', 'c']
rsplit()
Splits string from the right.
print("a,b,c".rsplit(",", 1)) # Output: ['a,b', 'c']
splitlines()
Splits string at line breaks.
print("line1\nline2".splitlines()) # Output: ['line1', 'line2']
join()
Joins elements of iterable with string as separator.
print(", ".join(["a", "b", "c"])) # Output: 'a, b, c'
Alignment and Padding
center()
Centers string with padding.
print("hello".center(11, "-")) # Output: '---hello---'
ljust()
Left-justifies the string.
print("hi".ljust(5, "*")) # Output: 'hi***'
rjust()
Right-justifies the string.
print("hi".rjust(5, "*")) # Output: '***hi'
zfill()
Pads string on the left with zeros.
print("42".zfill(5)) # Output: '00042'
Other Useful Methods
format()
Formats a string.
print("Hello, {}!".format("Alice")) # Output: 'Hello, Alice!'
format_map()
Similar to format()
but uses a dictionary.
print("{name}".format_map({"name": "Bob"})) # Output: 'Bob'
count()
Counts occurrences of a substring.
print("banana".count("a")) # Output: 3
partition()
Splits at first occurrence of separator.
print("key=value".partition("=")) # Output: ('key', '=', 'value')
rpartition()
Splits at last occurrence of separator.
print("key=value=final".rpartition("=")) # Output: ('key=value', '=', 'final')
maketrans()
and translate()
Create translation table and translate string.
trans = str.maketrans("ae", "12")
print("apple".translate(trans)) # Output: '1ppl2'
encode()
Encodes the string to bytes.
print("hello".encode()) # Output: b'hello'
Summary
Python strings come with a robust set of built-in methods that simplify many text-processing tasks. Mastery of these methods can greatly enhance your productivity and code readability.