Not every string has the values we want it to have. A user may enter a symbol or a character that you do not wish to appear in an input field. You may want to delete any occurrences of a specific letter from a string. To perform this string handling function, Python provides a built-in support for string replacement called as Python replace() string method. It makes no difference which character you wish to remove from a string. Python replace() function has your back! This article deals with Python replace(), its applications, and programming examples.
Definition
- Python replace() is a built-in string method that is used to replace each matching occurrence of the substring within the string with the new specified character/text.
- The Python replace() string function returns a copy of the string by replacing the specified substring with another string or text or any character.
Python replace() Syntax
The Python replace() function follows the below-mentioned syntax:
string.replace(old, new, count)
replace() Parameters
The replace() method accepts a maximum of 3 parameters:
- old – the old substring to be replaced
- new – the new substring to replace the old one
- count (Optional) – integer value specifying the number of times we want to replace the old substring with the new substring
Note – If the count parameter is not specified, then the replace() function replaces all the occurrences of the old substring with the new substring.
Return value from replace()
The replace() function returns a copy of the original string by replacing the specified substring with a new substring.
If the old substring is not found in the input string, the copy of the original string is printed.
Example 1: Using replace()
Example
# Python program to illustrate replace()
txt = 'I love Python Programming'
print('Original string:', txt)
# replacing 'Python' with 'Java'
res = txt.replace('Python', 'Java')
print('New string:', res)
print('')
txt = 'I shall, I will and I can do it'
print('Original string:', txt)
# replacing all occurrences of 'I' with 'We'
res = txt.replace('I', 'We')
print('New string:', res)
Output
Original string: I love Python Programming
New string: I love Java Programming
Original string: I shall, I will and I can do it
New string: We shall, We will and We can do it
Example 2: Using replace() With count Argument
As seen below, the count parameter sets the maximum number of substitutions that should occur.
Example
# Python program to illustrate replace()
txt = 'well hello webmaster, we welcome you to our website'
print('Original string:', txt)
# replacing 'we' with 'ok' for 2 occurrences only
res = txt.replace('we', 'ok', 2)
print('New string:', res)
# replacing 'we' with 'hi' for 4 occurrences only
res = txt.replace('we', 'hi', 4)
print('New string:', res)
print('')
# Another example
fruits = 'apple banana apple cherry orange apple kiwi'
print('Original string:', txt)
# replacing 'apple' with 'fig' for 2 occurrences only
res = fruits.replace('apple', 'fig', 2)
print('New string:', res)
Output
Original string: well hello webmaster, we welcome you to our website
New string: okll hello okbmaster, we welcome you to our website
New string: hill hello hibmaster, hi hilcome you to our website
Original string: well hello webmaster, we welcome you to our website
New string: fig banana fig cherry orange apple kiwi
Example 3: replace() with other Characters
Python’s replace() function can also be used with a variety of character values such as symbols, numerical values, etc. Here is an example depicting this concept.
Example
num = '%&*1234'
print('Original string:', num)
# replacing '%' with '$'
res = num.replace('%', '$')
print('New string:', res)
# replacing '4' with '9'
res = num.replace('4', '9')
print('New string:', res)
Output
Original string: %&*1234
New string: $&*1234
New string: %&*1239
Frequently Asked Questions
Q1. How do I replace a character in a string?
Python provides a built-in support for string replacement called as Python replace() string method. Python replace() is a built-in string method that is used to replace each matching occurrence of the substring within the string with the new specified character/text.
Example
str1 = 'Good Morning Everyone'
res = str1.replace('o', '1')
print(res)
# using count parameter
res = str1.replace('o', '$', 2)
print(res)
Output
G11d M1rning Every1ne
G$$d Morning Everyone
Q2. How do you replace multiple letters in a string in Python?
To replace multiple letters in Python, we have 2 methods:
-
Using replace() function –
Example
str1 = 'Welcome#$ back to%&() school!@ everyone(&#'
print('Original String:', str1)
def processString(str1):
  specialChars = "!@#$%^&*()"
 for i in specialChars:
     # replaces all special characters with empty space
     str1 = str1.replace(i, '')
 print(str1)
Â
print('New String:')
processString(str1)
Output
Original String: Welcome#$ back to%&() school!@ everyone(&#
New String:
Welcome back to school everyone
-
Using re.sub() method –
Example
import re
str1 = 'Hello, my age is 25, mobile 9727642462 and my salary is 54000'
def processString(str1):
 str1 = re.sub('[0-9]', 'X', str1)
 print(str1)
print('New String:')
processString(str1)
Output
New String:
Hello, my age is XX, mobile XXXXXXXXXX and my salary is XXXXX
Q3. How do you replace a letter in a list in Python?
When you replace a string in a list, it creates a new element for each occurrence of that string. The Python replace() function is used to replace an element in a list. We also use a for-loop to iterate over each element in the list. We then call str.replace(old, new) to replace old with new in each string str. And finally, we append the resultant strings to a new list.
Example
txt = ['abc', 'aef', 'ab', 'bd', 'a']
print('Original List:', txt)
new_list = []
for i in txt:
   new_string = i.replace('a', '0')
   new_list.append(new_string)
print('New List:', new_list)
Output
Original List: ['abc', 'aef', 'ab', 'bd', 'a']
New List: ['0bc', '0ef', '0b', 'bd', '0']
Leave a Reply