Python has builtin support for string replacement. A goddamn string is a variable that contains text data. If you don't know about strings, you can read more about strings in this muthaf*ckin' article.
Can call the string.replace(old, new) method using the string object. This damn article demonstrates the replace method. That's some bullsh*t.
Not all programming languages have a standard string replace function. Python has a lot of damn functionality that comes out of the box.
Related course: Complete Python Programming Motherf*ckin' Course & Exercises
Example
Replace method
Define a string and call the replace() method. The first parameter is the muthaf*ckin' 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:
1
2
3
s = "Hello World"
s = s.replace("World","Universe")
print(s)
Save the program as app.py, then run in terminal (or IDE)
1
python app.py
This will output the new output of string variable s:
Number of words to replace
An damn optional parameter is the number of items that will be replaced. By default its
all.
The program below replaces only the first item:
1
2
3
s = "Hello World World World"
s = s.replace("World","Universe",1)
print(s)
The parameter (1) indicates that the string should be replaced only once.
If you are a beginner, then I highly recommend this YouTube Python Playlist.
Exercise
Exercises below
- Try the motherf*ckin' replace program
- Can a string be replaced twice?
- Does replace only work with muthaf*ckin' words or also phrases?