Python String Replace method

The replace() method is responsible for substituting one phrase for another. If nothing else is supplied, all occurrences of the specified phrase are substituted. replace() is a Python built-in function that returns a string copy with all occurrences of a substring replaced with another substring.

You can use the Python method .replace() to replace all instances of a specified character with a new one. You can even specify a new line of text to replace an entire text string. The .replace() method returns a string copy. The old substring remains unchanged, but a new copy is made with the new text replacing all the old content.

Python String Replace method

The syntax is as follows:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>string.replace(oldvalue, newvalue, count)</pre>
</div>

Values of Parameters

  • oldvalue is needed. It refers to the phrase to look for in the given string.
  • newvalue is necessary. It is the string that will use to replace the old value.
  • count is Optional. It refers to a number indicating how many times you should replace the old value. All occurrences are the default.

Return Value of replace()

The replace() method copies the string and replaces the previous substring with the new substring. The original string has not been altered. If the old substring cannot be retrieved, the copy of the original string is returned.

Example: Python .replace() Method

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>original_string = "I am a Python coding expert on the fly."

# replacing all the instances of 'P' with 'K'
new_updated_phrase = original_string.replace("P", "K" )

print(original_string)
print(new_updated_phrase)

#output

#I am a Python coding expert on the fly
# I am a Kython coding expert on the fly</pre>
</div>

Each word containing the character ‘P’ is replaced with the character ‘K’ in the example above. There was a single instance of the letter P in that example. It was discovered in the word Python.

What if you merely wanted to add an ‘a’ instead of a ‘p’ to two terms, such as Python and coding?

How to Replace a Single Character in a Limited Number of Places

You’d use the count argument and set it to two to modify only two instances of a single character:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>original_string = "I am a Python coding expert on the fly."

# only replace the first two occurrences of 'o' with 'Q'
new_updated_phrase = original_string.replace("o", "Q", 2 )

print(original_string)
print(new_updated_phrase)

#output

# I am a Python coding expert on the fly
# I am a PythQn cQding expert on the fly</pre>
</div>

Set the count option to one if you just want to modify the first instance of a single character:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>original_string = "I am a Python coding expert on the fly."

# only replace the first occurrence of 'o' with 'Q'
new_updated_phrase = phrase.replace("o", "a", 1 )

print(original_string)
print(new_updated_phrase)

#output

# I am a Python coding expert on the fly
# I am a PythQn coding expert on the fly</pre>
</div>

How to Replace All String Instances

The procedure for changing several characters is similar.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>original_string = "The test is tough today. I don't really like a test."

# all instances of the word 'test' need replacement with 'CAT'
new_updated_phrase = phrase.replace("test", "CAT")

print(original_string)
print(new_updated_phrase)

#output

#The test is tough today. I don't really like a test.
#The CAT is tough today. I don't really like a CAT.
</pre>
</div>

The term ‘test’ is changed with the word CAT in the previous example.

How to Replace Only a Limited Number of String Instances

You would use the count option and set it to one if you simply wanted to transform the first instance of test to CAT.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>original_string  = "The test is tough today. I don't really like a test."

#replace only the first instance of the word 'test' with 'CAT'
new_updated_phrase = phrase.replace("test", "CAT", 1)

print(original_string )
print(new_updated_phrase)

#output

#The test is tough today. I don't really like a test.
#The CAT is tough today. I don't really like a test.</pre>
</div>

How to Substitute Case-Insensitive Substrings in Python

Consider the following scenario.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>original_string  = "I am an advanced Python coder. I really like what the python language offers. I hope it gets better programming in the Python language!"

#replace the text "Python" with "JAVA"
new_updated_phrase= phrase.replace("Python", "JAVA")

print(new_updated_phrase)

#output

#I am an advanced JAVA coder. I really like what the python language offers. I hope it gets better programming in the JAVA language!</pre>
</div>

What we actually wanted to accomplish in this scenario was to replace all instances of Python with JAVA. However, there was a lowercase ‘p’ in the term python, which we would like to fix as well.

It stayed the same and didn’t change to JAVA because the first letter was lowercase, not uppercase, as requested with Python. Because the .replace() method is case sensitive, it conducts case-sensitive substring substitutions. You’d have to do something different to accomplish a case-insensitive substring substitution. The re.sub() method and the re.IGNORECASE options would be required.

To use re.sub(), you must first:

  • Import re to use the re module.
  • Make a pattern of regular expressions.
  • Mention what you’d like to replace the pattern with.
  • Mention the string on which we will perform this action.
  • Optionally, specify the count option to fine-tune the replacement and the maximum number of replacements you want to do.
  • The re.IGNORECASE setting instructs the regular expression to match without regard for the case.

As a result, the syntax is as follows:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>import re

re.sub(pattern, replace, string, count, flags)</pre>
</div>

Using the above example as an example:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>import re

original_string  = "I am an advanced Python coder. I really like what the python language offers. I hope it gets better programming in the Python language!"

new_updated_phrase = re.sub("Python","JAVA", original_string, flags=re.IGNORECASE)

print(new_updated_phrase)

#output

#I am an advanced JAVA coder. I really like what the JAVA language offers. I hope it gets better programming in the JAVA language!</pre>
</div>

Example: replace the word “Apple”

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>laptops_strings = "Working for apple as a developer is my lifetime dream."

new_string = laptops_strings.replace("Apple", "Google")

print(new_string)</pre>
</div>

Example: Replacing all occurrences of the word “Google”:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>text_string = "Google is not just a search engine. Google is instead everything to any one working online. For instance, Google is simple home to developer."

result_string = text_string.replace("Google", "Yahoo")

print(result_string)</pre>
</div>

Example: Replacing the two initial occurrences of the word “Google”:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>text_string = "Google is not just a search engine. Google is instead everything to any one working online. For instance, Google is simple home to developer."

result_string = text_string.replace("one", "three", 2)

print(result_string)</pre>
</div>

Example: Using the method replace()

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>song_script = 'cold, cold heart'

# replacing 'cold' with 'hot'
print(song_script.replace('cold', 'hot'))


song_script = 'Let it be, let it be, let it be, let it be.'

# replacement of the two occurences of 'let'
print(song_script.replace('let', "Leave", 2))</pre>
</div>

Example: Te usage of replace() method

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>#!/usr/bin/python

original_str = "this is code snippet....wow!!! this is really great!!"
print original_str.replace("is", "was")
print original_str.replace("is", "was", 3)</pre>
</div>

Example: a program for demonstrating the use of replace() method

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>original_string = "coding for underscored underscored underscored underscored"

# Printint the string through replacement of all underscored by  Underscored
print(original_string.replace("underscored", "Underscored"))

# Printing the resultant string by replacement of the first 3 occurrence of  underscored
print(original_string .replace("underscored", "CodeUnderscored", 3))</pre>
</div>

Conclusion

With the help of examples, we have learned about the Python replace() method in this article. It replaces each old character/text occurrence in the string with the new character/text using the replace() method. The replace() function in Python returns a copy of the string with all occurrences of old replaced with new, with the number of replacements limited to max.

Similar Posts

Leave a Reply

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