Python: A Comprehensive Guide to String Methods

In Python, strings (str) are one of the most commonly used data types for representing textual information. Python’s string objects not only support indexing, slicing, and concatenation but also provide a rich set of methods for handling case conversion, searching and replacing, splitting and joining, alignment and padding, encoding and decoding, and more.

1. Case Conversion

lower()

Converts all letters in the string to lowercase..

upper()

Converts all letters in the string to uppercase.

print("mediaTEA".lower())   # mediateA
print("mediaTEA".upper())   # MEDIATEA

capitalize()

Capitalizes the first letter, making the rest lowercase.

title()

Capitalizes the first letter of each word.

print("hello world".capitalize())  # Hello world
print("hello world".title())  # Hello World

swapcase()

Swaps the case of each letter.

print("mediaTEA".swapcase())  # MEDIAtea

casefold()

A more aggressive lowercase conversion, primarily used for case-insensitive comparisons, stronger than lower()..

print("Straße".casefold())  # strasse
print("Python".casefold() == "PYTHON".casefold())  # True

Note: The case folding method in the Unicode standard is suitable for international applications that require “case-insensitive” handling.

2. Searching and Counting

find(sub[, start[, end]])

Returns the index of the first occurrence of substring sub in the string; returns -1 if not found..

Parameters:

sub: The substring to search for.

start (optional): The starting position for the search.

end (optional): The ending position for the search (exclusive).

Return value: Index (int), returns -1 if not found.

s = "banana"
print(s.find("na"))     # 2
print(s.find("na", 3))  # 4
print(s.find("xy"))     # -1

rfind(sub[, start[, end]])

Searches for sub from the right side, returning the last occurrence; returns -1 if not found..

index(sub[, start[, end]])

Same as find, but raises ValueError if not found.

rindex(sub[, start[, end]])

Same as rfind, but raises ValueError if not found.

print("banana".rfind("na"))  # 4
print("banana".index("na"))  # 2
print("banana".rindex("na"))  # 4

count(sub[, start[, end]])

Counts the occurrences of substring sub.

print("banana".count("na"))  # 2

3. Splitting and Joining

split(sep=None, maxsplit=-1)

Splits the string by the specified separator, returning a list..

Parameters:

sep: The separator, default is any whitespace.

maxsplit: The maximum number of splits, default is unlimited.

Return value: List.

s = "a b c"
print(s.split())        # ['a', 'b', 'c']
print(s.split(" ", 1))  # ['a', 'b c']

rsplit(sep=None, maxsplit=-1)

Splits from the right side, allowing for a specified maximum number of splits..

print("a b c".rsplit(" ", 1))  # ['a b', 'c']

splitlines([keepends])

Splits the string by lines.

Parameters:

keepends (optional): Defaults to False, meaning line breaks are not kept. If True, line breaks are kept.

s = "a\nb\nc"
print(s.splitlines())        # ['a', 'b', 'c']
print(s.splitlines(True))    # ['a\n', 'b\n', 'c']

partition(sep)

Divides the string into three parts based on the specified separator from the left: head, separator, tail..

rpartition(sep)

Divides the string into three parts based on the specified separator from the right: head, separator, tail..

print("hello mediaTEA world".partition(" "))  # ('hello', ' ', 'mediaTEA world')
print("hello mediaTEA world".rpartition(" ")) # ('hello mediaTEA', ' ', 'world')

join(iterable)

Joins multiple strings from an iterable into a new string, using the caller as the separator..

Parameters:

iterable: An iterable (like a list or tuple) where all elements must be strings; otherwise, a TypeError will be raised.

Return value:

The newly concatenated string.

words = ["a", "b", "c"]
print("-".join(words))   # a-b-c

4. String Content Checks

These methods typically return a boolean value to check if the string meets certain character conditions.

isalpha()

Checks if all characters are letters.

isalnum()

Checks if all characters are letters and numbers.

isdigit()

Checks if all characters are digits.

isdecimal()

Checks if it only contains “decimal digit characters” (more strict, commonly used for pure Arabic numeral checks).

isnumeric()

Checks if it only contains numeric characters (including Chinese numerals, etc.).

isspace()

Checks if it only contains whitespace characters.

print("abc".isalpha())   # True
print("abc123".isalnum())   # True
print("123".isdigit())      # True
print("123".isdecimal())  # True (full-width decimal)
print("一二三".isnumeric())  # True
print("   ".isspace())      # True

islower()

Checks if all characters are lowercase.

isupper()

Checks if all characters are uppercase.

istitle()

Checks if it is in title case (the first letter of each word is capitalized).

print("hello".islower())       # True
print("HELLO".isupper())       # True
print("Hello World".istitle()) # True

isascii()

Checks if all characters are ASCII characters.(3.7+)

print("abc".isascii())   # True
print("你好".isascii())  # False

isidentifier()

Checks if it is a valid Python identifier (can be used as a variable name).

print("user_name".isidentifier()) # True
print("3name".isidentifier()) # False

isprintable()

Checks if all characters are printable (spaces are also considered printable), non-printable characters include control characters (like newline \n, tab \t, etc.).

print("Hello".isprintable())    # True
print("Hello\nWorld".isprintable())  # False

startswith(prefix[, start[, end]])

Checks if the string starts with the specified prefix.

endswith(suffix[, start[, end]])

Checks if the string ends with the specified suffix.

print("hello".startswith("he"))  # True
print("hello".endswith("lo"))    # True

5. Alignment and Padding

ljust(width[, fillchar])

Left-aligns the string, padding the right side with spaces or a specified character..

Parameters:

width: Total width.

fillchar (optional): Padding character, default is space.

rjust(width[, fillchar])

Right-aligns the string, padding the left side with spaces or a specified character..

center(width[, fillchar])

Centers the string, padding both sides with spaces or a specified character..

print("hi".ljust(5, "-"))  # hi---
print("hi".rjust(5, "-"))   # ---hi
print("hi".center(5, "-"))  # --hi-

zfill(width)

Pads the left side with 0 until the specified width is reached..

print("42".zfill(5))  # 00042

6. Replacing and Deleting

replace(old, new[, count])

Replaces a substring.

Parameters:

old: The substring to be replaced.

new: The new substring.

count (optional): The number of replacements, default is all.

Return value: The new string.

s = "apple apple"
print(s.replace("apple", "orange"))      # orange orange
print(s.replace("apple", "orange", 1))   # orange apple

expandtabs(tabsize=8)

Expands tabs in the string to spaces, defaulting to 8 spaces per tab, which can be set via the parameter..

print("abc\tdef".expandtabs())       # 'abc     def'
print("abc\tdef".expandtabs(4))     # 'abc def'

format(*args, **kwargs)

Formats replacements using curly braces {} for positional or keyword arguments, suitable for constructing complex strings..

print("Hello, {}!".format("world"))              # 'Hello, world!'
print("{0} + {0} = {1}".format("a", "2a"))        # 'a + a = 2a'
print("{name} is {age} years old".format(name="mediaTEA", age=7))    # mediaTEA is 7 years old

Note:

*args: Positional arguments, can be referenced using {0}, {1}, etc.

**kwargs: Keyword arguments, can be referenced using {keyword}.

format_map(mapping)

Similar to format(), but only supports replacements using a dictionary (or any mapping object)..

data = {"name": "Alice", "age": 18}
print("{name} is {age}".format_map(data))  # Alice is 18

strip([chars])

Removes whitespace or specified characters from both ends of the string..

Parameters:

chars (optional): A set of characters to remove (note that this is not a substring).

print(" hello ".strip())      # "hello"
print("..hi..".strip("."))    # "hi"

lstrip([chars])

Removes whitespace or specified characters from the left side..

rstrip([chars])

Removes whitespace or specified characters from the right side..

print("xxhelloxx".lstrip("x"))  # "helloxx"
print("xxhelloxx".rstrip("x"))  # "xxhello"

removeprefix(prefix)

(Python 3.9+)If the string starts with the specified prefix, removes that prefix; otherwise returns the original string.

removesuffix(suffix)

(Python 3.9+)If the string ends with the specified suffix, removes that suffix; otherwise returns the original string.

print("unhappy".removeprefix("un"))     # happy
print("data.csv".removesuffix(".csv"))  # data
print("data.csv".removesuffix(".txt"))  # data.csv

7. Encoding and Decoding

encode(encoding=”utf-8″, errors=”strict”)

Encodes the string to a byte string (bytes), commonly used for text storage, network transmission, etc..

Parameters:

encoding: Optional. Encoding method, such as ‘utf-8’, ‘gbk’, ‘ascii’, etc., default is ‘utf-8’.

errors: Optional. Error handling method. Common values include:

‘strict’: Default, raises an error for characters that cannot be encoded.

‘ignore’: Ignores characters that cannot be encoded.

‘replace’: Replaces illegal characters with ‘?’ or U+FFFD.

Return value: A bytes type byte string.

print("你好".encode())              # b'\xe4\xbd\xa0\xe5\xa5\xbd'
print("abc".encode('ascii'))        # b'abc'
print("你好".encode('ascii', errors='ignore'))  # b''

bytes.decode(encoding=”utf-8″, errors=”strict”)

Decodes a byte string to a string.

b = b'\xe4\xbd\xa0\xe5\xa5\xbd'
print(b.decode("utf-8"))  # 你好

8. Other Methods

str.maketrans(mapping)

Generates a translation table based on mapping rules. (String class method)

translate(table)

Replaces or deletes characters in bulk based on the translation table generated by maketrans. More efficient than multiple replace()..

# 1. Establish mapping rules with two strings
table = str.maketrans("abc", "123")
print("abc cab".translate(table))  # Output: 123 321

# 2. Establish mapping rules with a dictionary
table = str.maketrans({"-": "", "_": " "})  # Remove "-", replace "_" with space
print("data-set_v1".translate(table))  # Output: dataset v1

# Remove characters using None:
table = str.maketrans({"a": None})
print("banana".translate(table))  # bnn   (removes all a)

📘 Summary

Case conversion: lower(), upper(), swapcase(), etc.

Searching and counting: find(), index(), count(), etc.

Splitting and joining: split(), splitlines(), partition(), join(), etc.

String content checks: isalpha(), isdigit(), isdecimal(), isidentifier(), isprintable(), etc.

Alignment and padding: ljust(), rjust(), center(), zfill(), etc.

Replacing and deleting: replace(), format(), strip(), rstrip(), removeprefix(), etc.

Encoding and decoding: encode() / decode()

Other methods: maketrans(), translate()

Python: A Comprehensive Guide to String MethodsLikes are meaningful, appreciation is encouragement

Leave a Comment