In python you can do string replace by method replace. It has several parameters:
- old string − This is old substring to be replaced.
- new string − This is the replacement of the old one.
- limit − This is a limit and only the first N occurrences are replaced. It's optional.
Basic string replace in python
Giving only two parameters of string method is enough to replace all occurrences of a substring:
str = "Java is very nice language. Java is number 1" print (str.replace("Java", "Python"))
Python is very nice language. Python is number 1
String replace with limit
Replacing first N occurrences in string can be done by adding max parameter:
str = "Java is very nice language. Java is number 1" print (str.replace("Java", "Python", 1))
Python is very nice language. Java is number 1
Alternative string replace in python
Since python string are special and can be treated as sequences of characters you can do : string[:4]
string = "Java rulez!" print(string[:4]) print(string[0:5] + "is boring")
Java is boring