sub
Lesson 5 of 28 in Coddy's RegEx in Python course.
The sub function is used to replace occurrences of a pattern in a string with a specified replacement string. It's a powerful tool for performing search-and-replace operations with regular expressions.
re.sub(pattern, repl, string, count=0)- pattern: The regular expression pattern to search for.
- repl: The replacement string.
- string: The string in which to search and replace.
- count: Optional. The maximum number of replacements to perform. The default value is 0, which means replace all occurrences.
import re
text = "I have 2 apples and 3 bananas."
pattern = r"\d" # This pattern matches any digit
replacement = "#"
result = re.sub(pattern, replacement, text)
print(result) # Output: I have # apples and # bananas.In the above example, we used the sub function to replace all digits in the string text with the replacement string "#". The result is a new string with the replacements made.
Challenge
EasyWrite a program that uses the sub function to replace all occurrences of the word "Python" with "JavaScript" in the string "Python is great. I love Python!". Print the result at the end.
Try it yourself
import re
text = "Python is great. I love Python!"
# Write code hereAll lessons in RegEx in Python
1Introduction
Introduction