How to Convert and Process Text in Python

This code cleans, converts, splits, joins, counts, replaces, reverses, and finds substrings in a text string using Python's standard string methods.

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

Python code

35 lines
Python 3.9+
text = "  hello world, python is fun!  "

# Clean up whitespace
cleaned = text.strip()

# Convert to title case
titled = cleaned.title()

# Split into words
words = cleaned.split()

# Join with hyphens
hyphenated = "-".join(words)

# Count occurrences of a letter
letter_count = cleaned.count("o")

# Replace a word
replaced = cleaned.replace("world", "universe")

# Reverse the text
reversed_text = cleaned[::-1]

# Find position of a substring
position = cleaned.find("python")

print(f"Original: '{text}'")
print(f"Cleaned: '{cleaned}'")
print(f"Title case: '{titled}'")
print(f"Words: {words}")
print(f"Hyphenated: {hyphenated}")
print(f"Count of 'o': {letter_count}")
print(f"Replaced: '{replaced}'")
print(f"Reversed: '{reversed_text}'")
print(f"Position of 'python': {position}")

Output

stdout
Original: '  hello world, python is fun!  '
Cleaned: 'hello world, python is fun!'
Title case: 'Hello World, Python Is Fun!'
Words: ['hello', 'world,', 'python', 'is', 'fun!']
Hyphenated: 'hello-world,-python-is-fun!'
Count of 'o': 4
Replaced: 'hello universe, python is fun!'
Reversed: '!nuf si nohtyp ,dlrow olleh'
Position of 'python': 12

How it works

The strip() method removes leading and trailing whitespace, making the string cleaner for further manipulation. title() capitalizes the first letter of each word, which is useful for headings and names. split() splits the string into a list of words based on whitespace, and join() merges list items with a specified separator. count() and replace() are straightforward for counting and substituting substrings, while slicing with [::-1] reverses the entire string. The find() method returns the index of the first occurrence of a substring or -1 if not found.

Common mistakes

  • Using `split(' ')` instead of `split()` can leave empty strings with multiple spaces.
  • Forgetting that `title()` capitalizes letters after punctuation, like 'world,' becoming 'World,'.
  • Assuming `replace()` changes the original string; it returns a new one.
  • Confusing `find()` with `index()`; `index()` raises an error if the substring is missing.

Variations

  1. Use `str.casefold()` for case-insensitive comparisons before counting.
  2. Use `re.sub()` from the `re` module for advanced pattern-based replacements.

Real-world use cases

  • Normalizing user input in a web form by stripping whitespace and converting to title case.
  • Building a search index by splitting text into words and counting frequencies.
  • Formatting file names or identifiers by joining words with hyphens.

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.