How to Generate Text Helper Functions in Python

Three simple Python functions that repeat, join, and count characters in strings for beginners.

Easy Python 3.9+ Aug 9, 2026 Strings & text 14 views 0 copies

Python code

23 lines
Python 3.9+
def repeat_text(text, times):
    """Repeat a string a given number of times."""
    return text * times


def join_words(words, separator=" "):
    """Join a list of words into a single string."""
    return separator.join(words)


def count_characters(text):
    """Count character occurrences in a string."""
    return {char: text.count(char) for char in set(text)}


if __name__ == "__main__":
    sample_text = "Hello Python!"
    
    print(f"Original: {sample_text}")
    print(f"Uppercase: {sample_text.upper()}")
    print(f"Repeated 3x: {repeat_text('ab', 3)}")
    print(f"Joined words: {join_words(['learn', 'python', 'today'], '-')}")
    print(f"Character counts: {count_characters('hello')}")

Output

stdout
Original: Hello Python!
Uppercase: HELLO PYTHON!
Repeated 3x: ababab
Joined words: learn-python-today
Character counts: {'h': 1, 'e': 1, 'l': 2, 'o': 1}

How it works

This code defines three reusable text helpers. repeat_text uses the multiplication operator, which Python strings support to duplicate a sequence. join_words leverages the str.join method, which is the idiomatic way to combine iterables of strings with a separator. count_characters builds a dictionary using a set comprehension to get unique characters, then counts each occurrence with str.count. The if __name__ == "__main__" block runs a demo only when the script is executed directly, not when imported.

Common mistakes

  • Using `+` to repeat a string instead of `*` which raises a TypeError for non-integer times.
  • Confusing `str.join` with formatting—careful that the separator is placed before `.join()`.
  • Counting characters with `for char in text` instead of `set(text)` which yields duplicate counts overwriting the dictionary.

Variations

  1. Use `collections.Counter` to count characters in one line: `Counter(text)`.
  2. Replace `join_words` with an f-string when the separator is fixed, e.g., `f"{words[0]}-{words[1]}"`.

Real-world use cases

  • Building report headers by repeating separator lines like `repeat_text('=', 40)` when formatting CLI output.
  • Creating slug strings for URLs by joining title words with hyphens using a join helper.
  • Generating a quick character frequency map for a lightweight text analysis script before more advanced NLP.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.