Python String Methods

·

7 min read

Python String Methods

Do you even string bro?

In Python programming, strings play a crucial role in storing and manipulating textual data. Python provides a vast array of string methods that can perform almost any operation on strings, making string handling in Python both efficient and straightforward. This blog post is a short intro to these methods, highlighting their uses and pointing out the subtle differences between methods that seem similar but are not.

Basic String Methods

Before we dive into the more nuanced methods, let's start with some basics. Methods like capitalize(), upper(), lower(), title(), and swapcase() are straightforward—they adjust the case of the string according to their names. For instance, capitalize() will uppercase the first letter of the string, while lower() will convert the entire string to lowercase.

Searching and Replacing

Methods such as find(), rfind(), index(), and rindex() are used to search for substrings within a string. The difference between find() and index() (and their reverse counterparts rfind() and rindex()) is in their behavior when the substring is not found: find() and rfind() return -1, whereas index() and rindex() throw a ValueError.

Replacing text is where replace() comes into play, allowing you to replace occurrences of a substring with another substring, potentially limiting the number of replacements with an optional argument.

Trimming and Adjusting

Python provides strip(), rstrip(), and lstrip() to trim whitespaces (or other specified characters) from the strings. These methods are incredibly useful for cleaning up user input or file data. center(), ljust(), and rjust() let you adjust the alignment of the string, padding it with spaces or specified characters.

Splitting and Joining

To cut a string into pieces, use split(), which divides a string into a list of substrings based on a delimiter. rsplit() does the same but starts splitting from the right. splitlines() is a specialized splitter that divides a string at line boundaries. Conversely, join() is used to concatenate an iterable of strings into a single string with a specified separator.

Advanced Manipulations

Python's string methods also include more sophisticated operations. For example, maketrans() and translate() work together to replace specified characters in a string, providing a powerful way to manipulate strings based on translation tables.

Subtly Different Methods: Decimals, Digits, and Numerics

Now, let's address the methods that seem similar but serve different purposes: isdecimal(), isdigit(), and isnumeric(). At first glance, these methods might appear interchangeable, but they cater to different sets of characters. isdecimal() checks if all characters in the string are decimal characters (0-9). isdigit() includes digits that are part of other numeral systems, like superscript 2 (²). Finally, isnumeric() encompasses a broader range of numeric characters, including digits, numeric characters like Roman numerals, and fractions.

New Additions: Prefix and Suffix Methods

Python 3.9 introduced removeprefix() and removesuffix() methods, simplifying the removal of a specific prefix or suffix from a string, if present. These methods enhance code readability and efficiency by eliminating the need for less intuitive string slicing operations.

Python String Methods Cheatsheet

This cheatsheet covers most of the commonly used string methods in Python. Note that some methods like maketrans() and translate() work together to replace specified characters in a string, offering a powerful way to manipulate strings based on translation tables.

Note: Some methods like isdecimal(), isnumeric(), and isdigit() seem similar, but they cater to different sets of characters. For instance, isdecimal() only considers decimal characters (0-9), isdigit() includes digits that are part of other numeral systems (like superscript 2, ²), and isnumeric() includes digits plus numeric characters (like Roman numerals, fractions).


# capitalize() - Converts the first character to upper case
example = "string methods"
print(example.capitalize())

# casefold() - Converts string to lower case, more aggressive than lower()
print(example.casefold())

# center(width, fillchar) - Returns a centered string, padded with specified character
print(example.center(20, "*"))

# count(sub, start, end) - Returns the number of times a specified value occurs in a string
print(example.count("o"))

# encode(encoding='utf-8', errors='strict') - Returns an encoded version of the string
print(example.encode())

# endswith(suffix, start, end) - Returns true if the string ends with the specified value
print(example.endswith("methods"))

# expandtabs(tabsize=8) - Sets the tab size of the string
tabs_example = "S\tT\tR\tI\tN\t\tG"
print(tabs_example.expandtabs(4))

# find(sub, start, end) - Searches the string for a specified value and returns the position of where it was found
print(example.find("methods"))

# format(*args, **kwargs) - Formats specified values in a string
print("Hello, {name}".format(name="John"))

# format_map(mapping) - Formats specified values in a string
print("Hello, {name}".format_map({"name": "John"}))

# index(sub, start, end) - Searches the string for a specified value and returns the position of where it was found
print(example.index("methods"))

# isalnum() - Returns True if all characters in the string are alphanumeric
print(example.isalnum())

# isalpha() - Returns True if all characters in the string are in the alphabet
print(example.isalpha())

# isascii() - Returns True if all characters in the string are ASCII
print(example.isascii())

# isdecimal() - Returns True if all characters in the string are decimals
print("123".isdecimal())

# isdigit() - Returns True if all characters in the string are digits
print("123".isdigit())

# isnumeric() - Returns True if all characters in the string are numeric
print("\u0030".isnumeric())

# isidentifier() - Returns True if the string is an identifier
print(example.isidentifier())

# islower() - Returns True if all characters in the string are lower case
print(example.islower())

# isprintable() - Returns True if all characters in the string are printable
print(example.isprintable())

# isspace() - Returns True if all characters in the string are whitespaces
print("   ".isspace())

# istitle() - Returns True if the string follows the rules of a title
print("String Methods".istitle())

# isupper() - Returns True if all characters in the string are upper case
print("STRING METHODS".isupper())

# join(iterable) - Joins the elements of an iterable to the end of the string
print(", ".join(["apple", "banana", "cherry"]))

# ljust(width, fillchar) - Returns a left justified version of the string
print(example.ljust(20, "*"))

# lower() - Converts a string into lower case
print("STRING METHODS".lower())

# lstrip(chars) - Returns a left trim version of the string
print("   string methods   ".lstrip())

# partition(sep) - Returns a tuple where the string is parted into three parts
print("string, methods".partition(" "))

# replace(old, new, count) - Returns a string where a specified value is replaced with a specified value
print(example.replace("h", "J"))

# rfind(sub, start, end) - Searches the string for a specified value and returns the last position of where it was found
print(example.rfind("o"))

# rindex(sub, start, end) - Searches the string for a specified value and returns the last position of where it was found
print(example.rindex("o"))

# rjust(width, fillchar) - Returns a right justified version of the string
print(example.rjust(20, "*"))

# rpartition(sep) - Returns a tuple where the string is parted into three parts
print("string, methods".rpartition(" "))

# rsplit(sep, maxsplit) - Splits the string at the specified separator, and returns a list
print("string, methods, test".rsplit(", "))

# rstrip(chars) - Returns a right trim version of the string
print("   string methods   ".rstrip())

# split(sep, maxsplit) - Splits the string at the specified separator, and returns a list
print(example.split())

# splitlines(keepends) - Splits the string at line breaks and returns a list
print("string\nmethods".splitlines())

# startswith(prefix, start, end) - Returns true if the string starts with the specified value
print(example.startswith("hello"))

# strip(chars) - Returns a trimmed version of the string
print("   string methods   ".strip())

# swapcase() - Swaps cases, lower case becomes upper case and vice versa
print("String Methods".swapcase())

# title() - Converts the first character of each word to upper case
print("string methods".title())

# translate(table) - Returns a translated string
trans = {ord("s"): "S", ord("m"): "M"}
print("string methods".translate(trans))

# upper() - Converts a string into upper case
print("string methods".upper())

# zfill(width) - Fills the string with a specified number of 0 values at the beginning
print("42".zfill(5))

# maketrans(x, y=None, z=None) - Returns a translation table to be used in translations
# This is a static method that doesn't require string object to call.
trans_table = str.maketrans("sm", "SM")
print("string methods".translate(trans_table))

# removeprefix(prefix) - Removes the prefix from the string, if it's present (Python 3.9 and later)
print("teststring methods".removeprefix("test"))

# removesuffix(suffix) - Removes the suffix from the string, if it's present (Python 3.9 and later)
print("string methodstest".removesuffix("test"))

Conclusion

Python's string methods offer powerful tools for text processing and manipulation, with a range of operations from basic case conversion to advanced searching, replacing, and trimming. Understanding the subtle differences between similar methods enhances your ability to write more efficient and readable code. By mastering these string methods, you can handle virtually any text processing task with ease and confidence.

Did you find this article valuable?

Support Timo by becoming a sponsor. Any amount is appreciated!