Welcome to CodeYourCraft's Python Tutorial on Substitution! Let's dive into the exciting world of Python programming, where we'll learn how to replace parts of our code with new values.
In Python, substitution (or replacement) is the process of replacing specific parts of a string with a new string. This is particularly useful when dealing with text manipulation, data cleaning, or even creating custom messages.
replace() Function ā
Python provides the replace() function for substitution. This function takes two arguments: the pattern we want to replace and the new string to replace it with.
text = "Hello, World!"
new_text = text.replace("Hello", "Hi")
print(new_text) # Output: "Hi, World!"š” Pro Tip: The replace() function is case-sensitive. If you want to replace all occurrences regardless of case, you can use the lower() function to convert both the original string and the pattern to lowercase before replacing.
If you need to replace multiple patterns, you can pass a list of patterns and new strings to the replace() function.
text = "The quick brown fox jumps over the lazy dog."
new_text = text.replace(["The", "quick", "jumps"], ["This", "slow", "runs"])
print(new_text) # Output: "This slow brown fox runs over the lazy dog."By default, the replace() function replaces the first occurrence of each pattern. To replace all occurrences at once, we can use the re.sub() function from the re module.
import re
text = "The quick brown fox jumps over the lazy dog. The quick brown fox jumps again."
new_text = re.sub(r"\bquick\b", "slow", text)
print(new_text) # Output: "The slow brown fox jumps over the lazy dog. The slow brown fox jumps again."š” Pro Tip: The re.sub() function uses regular expressions, so we've used the \b word boundary to ensure that we only replace "quick" when it's a separate word.
Python supports Unicode, so you can replace non-English characters just like English ones.
text = "Hola, Mundo!"
new_text = text.replace("Hola", "Hi")
print(new_text) # Output: "Hi, Mundo!"What does the `replace()` function do in Python?
By now, you should have a good understanding of how to replace parts of a string in Python using the replace() function. In the next lesson, we'll explore how to work with lists and arrays in Python. Happy coding! š