Python (Scripting) - Replace pattern using replace

by
Jeremy Canfield |
Updated: April 01 2024
| Python (Scripting) articles
There are two similar modules that can be used to replace a pattern.
- replace (non regular expression - this article)
- re.sub (regular expression)
In this example, replace is used to replace whitespace with %20.
#!/usr/bin/python
foo = "Hello World"
foo = foo.replace(" ", "%20")
print(foo)
Now the following should be printed.
Hello%20World
And here is how you can replace a pattern in elements in a list. In this example, Apple will be come Pear and Pineapple will not be changed.
#!/usr/bin/python3
fruit = ['Apple', 'Banana', 'Peach', 'Pineapple', 'Orange']
fruit = list(map(lambda x: x.replace('(?i)Apple', 'Pear'), fruit))
print(f"fruit = {fruit}")
Which should return the following.
fruit = ['Pear', 'Banana', 'Peach', 'Pineapple', 'Orange']
Did you find this article helpful?
If so, consider buying me a coffee over at