Can call the string.replace(old, new) method using the string object. This article demonstrates the replace method.
Not all programming languages have a standard string replace function. Python has a lot of functionality that comes out of the box.
Related course: Complete Python Programming Course & Exercises
Define a string and call the replace() method. The first parameter is the word to search, the second parameter specifies the new value.
The output needs to be saved in the string. If you don’t save the output, the string variable will contain the same contents. Saving output is done using: s = function()
Try the program below:
s = "Hello World"
s = s.replace("World","Universe")
Save the program as app.py, then run in terminal (or IDE)
This will output the new output of string variable s:
An optional parameter is the number of items that will be replaced. By default its all.
The program below replaces only the first item:
s = "Hello World World World"
s = s.replace("World","Universe",1)
The parameter (1) indicates that the string should be replaced only once.
If you are a beginner, then I highly recommend this book.
- Try the replace program
- Can a string be replaced twice?
- Does replace only work with words or also phrases?