String Functions in Python

The standard library’s string module provides many useful string-related functions. Here are some examples to give you a sense of the module.

import string

# We define a function to print with a shorter name as we'll use it a lot below.
def p(label, value):
    print(f"{label} {value}")

# Here's a sample of the functions available in the `string` module.
# Since these are functions from the module, not methods on the string object itself,
# we need to pass the string in question as an argument to the function.
# You can find more functions in the Python documentation for the `string` module.

p("Contains:  ", "es" in "test")
p("Count:     ", "test".count("t"))
p("StartsWith:", "test".startswith("te"))
p("EndsWith:  ", "test".endswith("st"))
p("Index:     ", "test".index("e"))
p("Join:      ", "-".join(["a", "b"]))
p("Repeat:    ", "a" * 5)
p("Replace:   ", "foo".replace("o", "0"))
p("Replace:   ", "foo".replace("o", "0", 1))
p("Split:     ", "a-b-c-d-e".split("-"))
p("ToLower:   ", "TEST".lower())
p("ToUpper:   ", "test".upper())

When you run this program, you’ll get:

$ python string_functions.py
Contains:   True
Count:      2
StartsWith: True
EndsWith:   True
Index:      1
Join:       a-b
Repeat:     aaaaa
Replace:    f00
Replace:    f0o
Split:      ['a', 'b', 'c', 'd', 'e']
ToLower:    test
ToUpper:    TEST

In Python, many of these operations are methods on string objects rather than standalone functions. The in operator is used for checking if a substring is contained in a string. The string module provides additional string constants and functions, but for basic string operations, Python’s built-in string methods are typically used.