Python String Functions: Examples and a Simple Program

Formulas & functions · Updated November 22, 2026

A Python string function program uses built-in string methods and functions such as strip(), lower(), split(), and len() to work with text. The example below is a complete program you can run: it tidies entered text, counts its words, and displays useful versions of the result.

def analyze_text(text):
    cleaned = " ".join(text.strip().split())
    words = cleaned.split()

    return {
        "cleaned": cleaned,
        "uppercase": cleaned.upper(),
        "lowercase": cleaned.lower(),
        "word_count": len(words),
        "starts_with_python": cleaned.lower().startswith("python")
    }

text = input("Enter some text: ")
result = analyze_text(text)

print("Cleaned:", result["cleaned"])
print("Uppercase:", result["uppercase"])
print("Lowercase:", result["lowercase"])
print("Word count:", result["word_count"])
print("Starts with Python:", result["starts_with_python"])

For example, if you enter Python is useful , the program cleans up the extra spaces, reports three words, and shows the text in uppercase and lowercase. Understanding the distinction between a function and a string method makes it easier to adapt this program to other text tasks.

What a Python String Function Means

A string is text stored as a str value, such as "hello" or "Order 123". In everyday descriptions, “string function” can refer either to a built-in Python function that accepts a string or to a method called on a string. Both are useful, but their syntax differs.

  • A built-in function is called by its name, with a value inside parentheses: len("hello") returns 5.
  • A string method is called after a string, separated by a dot: "hello".upper() returns "HELLO".

Python’s standard library also has modules with text-related tools, but most everyday string work needs no import. Methods such as replace(), find(), and split() are available directly on string values. The example program combines methods with built-in functions to handle a small, realistic task.

How the Example Program Works

The program defines analyze_text, a function that takes one argument named text. It first calls strip() to remove whitespace from the beginning and end. Then split(), with no separator provided, breaks the text into pieces at runs of whitespace. Joining those pieces with one space creates a cleaned version without leading, trailing, or repeated spaces.

Next, the program splits the cleaned text into a list named words. Calling len(words) counts the list items. This is a simple word count, not a linguistic analysis: punctuation remains attached to words, and a hyphenated expression normally counts as one item. The returned dictionary groups the results under descriptive keys, so later code can refer to result["word_count"] rather than relying on the order of several separate values.

Finally, input() reads a line typed by the user. The function processes that line, and the print() calls display the returned values. This separation is useful: the text-processing function can be called again with another string without repeating the input and output code.

Useful String Methods and Built-In Functions

Python provides many string methods, but a small group covers a large share of common tasks. These examples can be run individually in a Python prompt or saved in a script.

  • text.strip() removes whitespace at both ends; text.lstrip() and text.rstrip() target the left or right end.
  • text.lower() and text.upper() return lowercase and uppercase versions. text.title() applies title-style capitalization, though it may not suit every name or writing style.
  • text.replace("old", "new") returns a copy with matching occurrences replaced. By default, it replaces every non-overlapping match.
  • text.find("part") returns the first matching position, or -1 if the substring is absent. text.count("a") counts non-overlapping occurrences.
  • text.startswith("pre") and text.endswith(".txt") test the beginning and end, returning True or False.
  • len(text) returns the number of characters in the string. It is a built-in function, not a method, so it is written with the string inside its parentheses.

For example, with text = " Python Basics ", text.strip() produces "Python Basics", and text.lower() produces " python basics ". Lowercasing alone does not remove spaces; each operation does only its own job.

Splitting Text and Joining It Again

split() is especially useful when a string contains several values separated by spaces, commas, or another known delimiter. With no argument, "red blue green".split() returns ["red", "blue", "green"]; repeated whitespace does not create empty items. With a comma as the separator, "red,blue,green".split(",") returns three pieces.

The reverse operation is join(), which belongs to the separator string. For example, ", ".join(["red", "blue", "green"]) creates "red, blue, green". Every item supplied to join() must be a string. If a list includes numbers, convert them first, for example with str(number), or use a formatting approach that handles the values explicitly.

Splitting on commas is not a complete way to read every CSV file. Real CSV data may contain quoted commas, line breaks, and escaping rules. For files in that format, Python’s csv module is more reliable than manually calling split(","). Use simple splitting for simple, controlled input; use a dedicated parser when the format has rules of its own.

Formatting Strings with Values

Programs often need to combine text with numbers or other values. F-strings provide a readable option: name = "Mina" followed by message = f"Hello, {name}!" creates "Hello, Mina!". An expression can also appear inside braces, as in f"Total: {price * quantity:.2f}", where :.2f displays a number with two digits after the decimal point.

F-strings are part of modern Python and are available from Python 3.6 onward. For older code or a string template that will be filled later, the format() method is another option: "Hello, {}!".format(name). Avoid using string concatenation as a substitute for formatting when values may not be strings. For instance, combining a string and an integer directly with + raises a TypeError; convert the value or format it.

Writing a Custom Function for Text

Built-in methods perform common operations, while a custom function gives a task a reusable name and can combine several operations with clear rules. For example, a program might need to normalize a user-entered label before comparing it:

def normalize_label(label):
    """Trim outer spaces and compare labels without case differences."""
    return label.strip().casefold()

first = normalize_label("  North Wing ")
second = normalize_label("north wing")
print(first == second)  # True

casefold() is intended for caseless text matching and handles some Unicode case differences more thoroughly than lower(). That does not mean it should replace the original display text: it returns a normalized value for comparison. Keep the original string when you need to preserve the user’s capitalization or formatting.

A useful custom function should express a specific rule, such as trimming a label or validating an identifier, rather than merely giving an unnecessary new name to a method. Consider documenting what the function changes and what it leaves alone. If the function transforms input, returning a new string makes that behavior explicit and avoids surprising changes elsewhere in the program.

Immutability, Unicode, and Common Mistakes

Python strings are immutable. A method such as upper() does not modify the existing string in place; it returns a new string. Thus, after text.upper(), the variable text still refers to its original value unless the result is assigned, as in text = text.upper(). This is a frequent source of confusion for people who expect a method call to change the value automatically.

Another common mistake is mixing up the method and its result. text.find("x") gives an integer position, not a string, while text.replace("x", "y") gives a string. Use in when the only question is whether a substring exists: "py" in "python" evaluates to True. It is often clearer than checking whether find() returned a nonnegative number.

Text is Unicode, so “character count” can require care. len() counts Python string elements, which are Unicode code points, rather than bytes. Some visible symbols are composed of multiple code points; emoji and accented text can therefore make a displayed character count differ from len(). For ordinary word processing this distinction may not matter, but it matters when a specification requires counting user-perceived characters or measuring encoded data.

String methods also distinguish upper- and lowercase text unless a method explicitly supports another behavior. For a case-insensitive prefix test, one option is to compare text.lower().startswith("python"), as the sample program does. For Unicode-aware caseless comparison, use casefold(). Neither operation changes the original value unless its result is stored.

Choosing the Right Tool

Start by stating the task precisely. If you need a character count, use len(); if you need to remove outside spaces, use strip(); if you need tokens, use split(); and if you need a readable message containing values, use an f-string. Choosing a direct method usually makes code easier to understand than building a custom loop for a standard operation.

For validation, remember that a string method can check a basic property but does not automatically establish that input is safe or valid for every later use. For example, isdigit() can help identify strings made up of digit characters, but it does not check whether a value fits a particular business rule or numeric range. Convert and validate according to the data you expect, and handle conversion errors where user input may be malformed.

For repeated work on large amounts of text, built-in methods are generally a clear starting point. If requirements involve language-aware tokenization, complex patterns, structured files, or specialized Unicode normalization, use an appropriate standard-library module or a well-established package rather than trying to make one string method solve a larger parsing problem.

Frequently Asked Questions

What is the string function in Python?

Python has several string methods rather than one universal string function. Common choices include upper(), lower(), strip(), replace(), and split(). Built-in functions such as len() also work with strings.

How do I write a Python program to reverse a string?

For a simple reversal, assign text[::-1] to a variable or print it directly. For example, "python"[::-1] produces "nohtyp". This reverses the sequence of code points, which may not preserve complex visible characters made from multiple code points.

How can I count words in a string?

For a basic whitespace-separated count, use len(text.split()). It treats runs of whitespace as separators and returns zero for an empty or whitespace-only string. It does not account for punctuation rules, abbreviations, or language-specific word boundaries.

Do Python string methods change the original string?

No. Strings are immutable, so methods such as strip() and replace() return new strings. To keep a transformed result, assign it to a variable, for example text = text.strip().

What is the difference between find() and index()?

Both search for a substring and return its position when found. find() returns -1 when there is no match, while index() raises a ValueError. Use find() when a missing match is an expected possibility, or use in if you only need a yes-or-no check.

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.