Bootstrap FreeKB - Python (Scripting) - Replace pattern using replace
Python (Scripting) - Replace pattern using replace

Updated:   |  Python (Scripting) articles

There are two similar modules that can be used to replace a pattern.

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 Buy Me A Coffee



Comments


Add a Comment


Please enter d712fd in the box below so that we can be sure you are a human.