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.
Python code
35 linestext = " 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
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
- Use `str.casefold()` for case-insensitive comparisons before counting.
- 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
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.