How to Replace Substrings in Python Strings?

Replacing substrings within a string is a common task in Python. The replace() method allows you to replace occurrences of a substring with another substring.

Basic Syntax

string.replace(old, new, count)

Where:

  • old: The substring you want to replace.
  • new: The substring you want to replace it with.
  • count: (Optional) Number of occurrences to replace.

Example Usage

text = "Hello World"
new_text = text.replace("World", "Python")
print(new_text)  # Output: Hello Python

Replacing Multiple Occurrences

Replace all occurrences of a substring:

text = "banana"
new_text = text.replace("a", "o")
print(new_text)  # Output: bonono

Limiting Replacements

Use the count parameter to limit replacements:

new_text = text.replace("a", "o", 1)
print(new_text)  # Output: bonana

Conclusion

The replace() method is a straightforward way to manipulate strings in Python. It’s essential for text processing and data cleaning tasks.

Leave a Reply

Your email address will not be published. Required fields are marked *