Wednesday, January 15, 2025
HomeTechPython String replace() Method

Python String replace() Method

The replace() method in Python is used to replace a specified substring with another substring within a string. It creates a new string with the replacement since strings in Python are immutable.

Syntax

python
str.replace(old, new, count)
  • old: The substring to be replaced.
  • new: The substring to replace old.
  • count (optional): The number of occurrences to replace. If omitted, all occurrences will be replaced.

Examples

1. Replace All Occurrences

python
text = "Hello, World! Welcome to the World!"
new_text = text.replace("World", "Python")
print(new_text)

Output:

css
Hello, Python! Welcome to the Python!

2. Replace Limited Occurrences

python
text = "apple apple apple"
new_text = text.replace("apple", "orange", 2)
print(new_text)

Output:

orange orange apple

3. Case-Sensitive Replacement

The replace() method is case-sensitive, so it differentiates between uppercase and lowercase.

python
text = "Hello World"
new_text = text.replace("world", "Python")
print(new_text)

Output:

Hello World

4. Replacing Spaces or Special Characters

python
text = "Python is fun!"
new_text = text.replace(" ", "_")
print(new_text)

Output:

Python_is_fun!

5. Using replace() with Empty String

You can remove a substring by replacing it with an empty string.

python
text = "Remove unwanted words."
new_text = text.replace("unwanted ", "")
print(new_text)

Output:

mathematica
Remove words.

Key Points

  1. Immutability: The replace() method doesn’t modify the original string; it returns a new string.
  2. Case-Sensitivity: Matches are case-sensitive.
  3. Efficient for Replacements: Suitable for replacing specific substrings.
See also  How Can I Convert an Ultra Hdr Image to Jxr, Retaining Hdr Information?

Common Use Cases

  • Replacing specific words in a document.
  • Formatting strings (e.g., replacing spaces with underscores).
  • Removing unwanted characters from a string.

The replace() method is versatile and frequently used for text manipulation in Python.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x