How do you replace a specific value in a string Python?

To replace a string in Python, use the string.replace() method. The replace() method accepts three arguments and replaces the specified phrase with another specified phrase.

Python string replace()

The string replace() is a built-in Python function that returns the copy of the string where all occurrences of the substring are replaced with another substring. 

The replace() function returns the copy of the string in which the values of the old string have been replaced with a new value. The replace() method does not modify the original string.

In Python, everything is an object, and the string is an object too. Thus, Python strings can be created simply by enclosing characters in a double quote.

Often you will have the string (str object), where you want to modify the contents by replacing one text with another.

Syntax

The syntax of the Python string replace function is the following.

string.replace(oldvalue, newvalue, count)

Parameters

The oldvalue parameter is required, which is the value we need to search for.

The newvalue parameter is required, which is the value we need to replace.

The count parameter is optional and a number specifying how many occurrences of the old value you want to replace.

Return Value

The replace() method returns the copy of the string where the old substring is replaced with the new substring — one thing to keep in mind is that the original string is unchanged.

If an old substring is not found, it returns the copy of an original string.

The replace() is a method of <class ‘str’> in python3.

Example

# app.py

line = 'Every DC Movies are great movies'

replacedString = line.replace('DC', 'Marvel')

print(replacedString)

We are replacing the DC substring with the Marvel in the above example.

See the output below.

How do you replace a specific value in a string Python?

Here one thing is to notice that the original string is unchanged.

Let’s see the example where we will specify how many times you need to change the occurrences.

# app.py

line = 'Every DC Movies are great Movies!! Really great Movies'

replacedString = line.replace('Movies', 'Cartoons', 2)

print(replacedString)

In the above example, we are changing only two times from Movies to Cartoons.

How do you replace a specific value in a string Python?

Implementation of String replace() method

To implement the replace() method in Python, define a string and then replace the characters of that string with a different one and then see the output.

# app.py

str = 'cold, cold heart'
replaced_str =  str.replace('o', 'e')
print ('Original string:', str)
print ('Replaced string:', replaced_str)

str = 'let it be, let it be, let it be'
print(str.replace('let', 'so', 0))

See the output.

How do you replace a specific value in a string Python?

How to replace multiple characters in Python string

To replace multiple characters in a string in Python, use the chaining of string.replace() methods. Replacing multiple characters in a string creates a new string with the replaced characters.

main_str = "Millie Bobby Brown"

# printing original string
print("The original string is : " + str(main_str))

# Using nested replace()
# Replace multiple characters at once
res = main_str.replace('M', "L").replace('B', 'G')

# printing result
print("The string after replacement of positions : " + res)

Output

The original string is : Millie Bobby Brown
The string after replacement of positions: Lillie Gobby Grown

You can see that L replaces the M character, and G replaces the B character.

Python replace() with user input.

To get the input from the user, use the input() method. Let’s see the following example: a user input string replaces the string.

#app.py

inputStr = input('Please provide input string\n')
delimiter = input('Please provide delimiter\n')
delimiter_new = input('Please provide new delimiter\n')
newStr = inputStr.replace(delimiter, delimiter_new)
print('Replaced Data =', newStr)

See the output.

➜  pyt python3 app.py
Please provide input string
mike is good character from strangerthings
Please provide delimiter
mike
Please provide new delimiter
eleven
Replaced Data = eleven is good character from strangerthings
➜  pyt

Python string replace regex.

Python string.replace() method does not recognize regular expressions. To use the regular expression in Python, import the re module and then use the method sub().

#app.py

import re

data = "The rain in Australia"
res = re.sub("\s", "||", data)
print(res)

See the output.

➜  pyt python3 app.py
The||rain||in||Australia
➜  pyt

How to replace special characters in Python string

To replace special characters in Python string, import the re module and use the re.sub() method. When you want to replace a special character, use regular expressions.

Again, you should use the regular expression to replace the special characters.

# app.py

line = 'Every DC Movies are great movies'

replacedString = line.replace('DC', 'Marvel')

print(replacedString)
0

See the output.

# app.py

line = 'Every DC Movies are great movies'

replacedString = line.replace('DC', 'Marvel')

print(replacedString)
1

How to replace Character at Specific Index in String

To replace a character at a specific index in a string in Python, use python string slicing.

# app.py

line = 'Every DC Movies are great movies'

replacedString = line.replace('DC', 'Marvel')

print(replacedString)
2

Here the character is a new character that has to be replaced, and position is the index at which we replace the character.

# app.py

line = 'Every DC Movies are great movies'

replacedString = line.replace('DC', 'Marvel')

print(replacedString)
3

Output

# app.py

line = 'Every DC Movies are great movies'

replacedString = line.replace('DC', 'Marvel')

print(replacedString)
4

As you can see from the output, we have replaced a character r with k. So the dataframe becomes a dataframe.

Python replace() backslashes with slashes.

To replace a backslash with a slash in Python, use the string.replace() method. Pass the backslash as an old character and pass the slash as a replacement character to replace the backslash with a slash.

# app.py

line = 'Every DC Movies are great movies'

replacedString = line.replace('DC', 'Marvel')

print(replacedString)
5

See the output.

# app.py

line = 'Every DC Movies are great movies'

replacedString = line.replace('DC', 'Marvel')

print(replacedString)
6

As you can see that the double backslash is replaced with a forwarding slash using the replace() method.

Conclusion

Hopefully, the above article would have given you a fair idea of using Python’s string replace() method.

How do you replace a specific value in a string?

The replace() method searches a string for a value or a regular expression. The replace() method returns a new string with the value(s) replaced. The replace() method does not change the original string.

How do you replace a specific part of a string with something else Python?

In Python, the . replace() method and the re. sub() function are often used to clean up text by removing strings or substrings or replacing them.

How do you replace only one occurrence of a string in Python?

replace (old, new[, count]) -> string Return a copy of string S with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

How to replace all occurrences of a character in a string Python?

The replace() method replace() is a built-in method in Python that replaces all the occurrences of the old character with the new character.