This tutorial help to replace character in a string. We’ll discuss different ways to replace characters in a string. I also let you know to replace special characters and substring them into a string.
How To Replace Characters in Python
You can replace any char with a respective char at a given index.
s = 'I am pythonpip.com' index = 7 char = 'i' rep_s = s[:index] + char + s[index + 1:] print(rep_s)
Output :
I am pyihonpip.com
Python Replace Substring
Syntax :
The replace()
is a Python built-in function that returns a string copy with all occurrences of a substring replaced with another substring. It returns a string copy with all occurrences of a substring replaced by another substring.
string.replace(old, new, count)
Whereas:
- old – What you want to replace.
- new – Which would replace the old substring.
- count – This is Optional. The number of times you wish to use the new substring to replace the old one.
Python replace all occurrences in string
Let’s create a simple python code that helps to understand the python replace() method.
string = "Dali Dali Pe Nazar Dali, Kisine Achchi Dali, Kisine Buri Dali, Jis Dali Par Maine Nazar Dali Wo Dali Kisine Tod Dali" # Prints the string by replacing all print(string.replace("Dali", "Stalk"))
Output :
Stalk Stalk Pe Nazar Stalk, Kisine Achchi Stalk, Kisine Buri Stalk, Jis Stalk Par Maine Nazar Stalk Wo Stalk Kisine Tod Stalk
Python replace multiple Substring
Let’s create a simple python code that replace multiple substring in a string.
string = "Dali Dali Pe Nazar Dali, Kisine Achchi Dali, Kisine Buri Dali, Jis Dali Par Maine Nazar Dali Wo Dali Kisine Tod Dali" # Prints the string by replacing 2 print(string.replace("Dali", "Stalk", 2))
Output :
Stalk Stalk Pe Nazar Dali, Kisine Achchi Dali, Kisine Buri Dali, Jis Dali Par Maine Nazar Dali Wo Dali Kisine Tod Dali
Python string replace multiple characters
Let’s create a simple python code that replace multiple characters in a string.
string = “a:b:c:d”
Replace all
print(string.replace(':', ','))
Output :
a,b,c,d