0
0
Pythonprogramming~5 mins

Searching and replacing text in Python

Choose your learning style9 modes available
Introduction

Sometimes you want to find certain words or parts in a text and change them to something else. This helps fix mistakes or update information quickly.

Fixing typos in a document automatically.
Changing a name or date in many places in a text.
Updating old words to new ones in a story or article.
Removing unwanted characters from user input.
Syntax
Python
new_text = original_text.replace('old', 'new')

The replace method creates a new string; it does not change the original text.

You can replace all occurrences or limit how many to replace by adding a third numeric argument.

Examples
This changes 'cats' to 'dogs' in the sentence.
Python
text = 'I like cats'
new_text = text.replace('cats', 'dogs')
print(new_text)
This replaces only the first two 'hello' words with 'hi'.
Python
text = 'hello hello hello'
new_text = text.replace('hello', 'hi', 2)
print(new_text)
This removes all dashes from the phone number.
Python
text = '123-456-7890'
new_text = text.replace('-', '')
print(new_text)
Sample Program

This program shows how to find the word 'fox' and replace it with 'cat'. It prints both the original and the changed sentence.

Python
original = 'The quick brown fox jumps over the lazy dog.'
changed = original.replace('fox', 'cat')
print('Original:', original)
print('Changed:', changed)
OutputSuccess
Important Notes

Remember, strings in Python cannot be changed directly; replace returns a new string.

If the word to replace is not found, the original string stays the same.

You can chain multiple replace calls to change several words.

Summary

Use replace to find and change parts of text easily.

It returns a new string and does not modify the original.

You can control how many replacements happen with an optional number.