Python String Functions: Syntax and Examples

Formulas & functions · Updated November 22, 2026

Python string functions are mostly methods called on a string, such as text.lower(), text.replace(old, new), and text.split(sep); built-in functions such as len(text) take a string as an argument. The basic syntax is string.method(arguments), and the right method depends on whether you want to change, search, split, format, or check text.

What Python Means by String Functions

A Python string is a sequence of Unicode characters, written using single quotes, double quotes, or triple quotes. For example, name = "Mina" assigns a string to a variable. Python’s str type provides many operations for working with that text. People often call all of these operations “string functions,” but most are technically methods: they belong to a string object and are called after a dot.

That distinction explains the two common forms. A method looks like name.upper(); a built-in function looks like len(name) or str(42). Methods can take arguments inside their parentheses, but some take none. For instance, name.upper() has no arguments, while name.replace("M", "N") has two. Parentheses are required to call a method; writing name.upper by itself refers to the method rather than calling it.

Strings are immutable. A method that appears to change text returns a new string instead of editing the original one in place. Assign the result if you want to keep it: name = name.upper(). This behavior is useful to remember when a method call seems to have had no effect.

Basic Syntax and Calling Methods

The general method pattern is value.method(argument1, argument2). The value before the dot is the string being operated on, and arguments in parentheses supply optional details. You can call a method directly on a string literal, too: "hello".capitalize() returns "Hello". If an argument is itself a string, put it in quotes.

Methods can be chained because many return strings. For example, " PyThOn ".strip().lower() first removes surrounding whitespace, then lowercases the remaining text, producing "python". Chaining is concise, but break a long chain into separate statements if that makes its order easier to understand.

Use Python’s interactive help when you need a method’s precise signature: help(str.split) displays documentation for the method. The official built-in types documentation is another useful reference, especially when an optional argument changes how a method behaves.

Changing Case and Cleaning Text

Case-conversion methods return new strings. Common choices include upper() for uppercase, lower() for lowercase, capitalize() for an initial capital with the rest lowercased, and title() for title-style capitalization. These are convenient for display or simple comparisons, but title casing is not a complete set of language-specific writing rules. For case-insensitive comparisons involving Unicode text, casefold() is designed to be more thorough than lower().

Whitespace and unwanted edge characters can be removed with strip(), lstrip(), and rstrip(). They remove characters from both ends, the left end, or the right end respectively. With no argument, they remove whitespace such as spaces, tabs, and newlines. With an argument, they treat it as a set of characters to trim, not as one exact prefix or suffix.

message = "  Hello, Python!  "
clean = message.strip()
print(clean)  # Hello, Python!
print(clean.lower())  # hello, python!

If you need to remove a particular prefix or suffix, use removeprefix() or removesuffix() rather than passing that text to strip(). For example, "unhappy".removeprefix("un") returns "happy", while "unhappy".strip("un") removes any matching characters from both ends and can produce a different result. The prefix and suffix methods were added in Python 3.9.

Finding and Replacing Text

Use find(substring) to get the position of a substring’s first occurrence. Python indexes start at zero, so "banana".find("na") returns 2. If the substring is absent, find() returns -1. The related index() method also searches, but raises ValueError when it finds no match. Choose find() when absence is an expected possibility; use index() when a missing match should be treated as an error.

For a yes-or-no check, substring in text is often clearer than checking a search position. Use startswith(prefix) and endswith(suffix) to test the beginning or end of a string. Both can accept a tuple of alternatives, as in filename.endswith((".jpg", ".png")).

replace(old, new, count) returns a copy with occurrences of old replaced by new. The optional count limits how many replacements are made from left to right. For example, "red red red".replace("red", "blue", 1) returns "blue red red". To count non-overlapping occurrences without replacing them, use count(substring).

Splitting, Joining, and Partitioning

split() divides a string into a list. With no separator, it groups runs of whitespace and omits empty pieces at the ends: " one two ".split() returns ["one", "two"]. Provide a separator when the format has a specific delimiter: "a,b,c".split(",") returns ["a", "b", "c"]. The optional maxsplit argument limits the number of splits.

There is an important difference between split() and split(" "). The latter splits only at literal space characters, so repeated spaces can create empty strings in the result. For line-oriented text, splitlines() splits at line boundaries. When you need just the first separator and its surrounding parts, partition(sep) returns a three-item tuple: the part before the first match, the separator, and the part after it. If no match exists, the separator and final part are empty strings.

The inverse of joining a list with a separator is often written using join(): the separator is the string before the dot, and the pieces are passed as an iterable. For example, ", ".join(["red", "green", "blue"]) returns "red, green, blue". Every item must be a string; convert numbers explicitly if needed, such as with str(number). This method is generally preferable to repeatedly adding strings in a loop when assembling many pieces.

Formatting Values into Strings

Formatted strings, usually called f-strings, are a direct way to place expressions inside text. Put an f before the opening quote and surround each expression with braces: f"Hello, {name}!". Format specifications follow a colon inside the braces. For instance, f"{price:.2f}" displays a numeric value with two digits after the decimal point. F-strings are available in Python 3.6 and later.

The format() method is another option: "Hello, {}!".format(name). Numbered or named fields help when the template is reused or values are supplied in a different order, as in "{item}: {count}".format(item="apples", count=3). Older code may use the percent operator, such as "%s" % name; it remains supported, though f-strings are often easier to read in modern Python.

Formatting controls presentation, not the underlying value. A formatted number becomes text, so do numeric calculations before formatting if you still need arithmetic. For user-provided text, also avoid assuming that inserting a value into a string automatically makes it safe for every destination. HTML, SQL, shell commands, and other contexts have their own escaping or parameterization requirements.

Checking What a String Contains

String predicates return Boolean values, making them useful in conditions. Examples include isalpha() for alphabetic characters, isdigit() for digit characters, isalnum() for alphanumeric characters, isspace() for whitespace, and islower() or isupper() for case. For example, "abc123".isalnum() is True, while "abc 123".isalnum() is False because of the space.

These checks have details that matter for validation. Most are Unicode-aware, so “digit” is not always limited to the ASCII characters 0 through 9. Also, an empty string generally makes these checks return False. If a field must follow a strict format, such as an ASCII-only identifier or a fixed postal code pattern, a single is... method may not express the full rule. Combine checks or use a regular expression when the format is more specific.

Common Mistakes and Practical Choices

  • Forgetting to save the result: text.strip() returns a cleaned string but does not update text. Use text = text.strip() when that is the intended value.
  • Using strip() as exact removal: it removes any characters in the supplied set from the edges. Use removeprefix() or removesuffix() for a specific string.
  • Assuming find() raises an error: it returns -1 when no match exists. Use index() if you want a missing substring to raise an exception.
  • Confusing a method with a built-in: write len(text), not text.len(); write text.lower(), not lower(text).
  • Expecting a string to be a list: strings are sequences, but methods such as split() create a list. Use join() to combine string pieces again.

For everyday work, choose the operation that states your intent most plainly: in for containment, startswith() for a prefix check, split() for tokenizing, join() for assembling pieces, and an f-string for readable interpolation. A short method chain is handy for routine cleanup, while explicit intermediate variables are easier to inspect when debugging or handling complex input.

Frequently Asked Questions

What is the syntax of a string method in Python?
A string method is called on a string with a dot and parentheses: text.method(arguments). For example, text.replace("-", " ") returns a string with hyphens replaced by spaces.

What is the difference between a string function and a string method?
A method belongs to a string and is called after it, as in text.upper(). A built-in function is called by name and can receive a string as an argument, as in len(text). “String function” is commonly used informally for both.

How do I convert a string to lowercase in Python?
Call lower(), for example "HELLO".lower(), which returns "hello". For more comprehensive Unicode case-insensitive matching, consider casefold().

How do I remove spaces from a string?
Use strip() to remove whitespace at both ends, or lstrip() and rstrip() for one side. To remove spaces throughout the text, use replace(" ", ""); that removes ordinary space characters, not every possible kind of whitespace.

Do Python string methods change the original string?
No. Strings are immutable, so methods such as replace() and lower() return new strings. Assign the returned value to a variable if you want to retain the result.

Related

Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.

More in Formulas & functions

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.