re.sub()
RegexReplaces occurrences of the pattern with the replacement string.
Signature
re.sub(pattern, repl, string, count=0)
Returns
strExample
import re result = re.sub(r'\s+', ' ', 'hello world foo') print(result) # 'hello world foo'
About re.sub()
re.sub is a Python regex function with the signature re.sub(pattern, repl, string, count=0). Replaces occurrences of the pattern with the replacement string. It returns a value of type str.
Python provides a rich set of built-in functions and standard library modules that cover common programming tasks. Understanding these functions helps you write more idiomatic, efficient Python code. The re.subfunction is commonly used in data processing, web development, scripting, and automation tasks.
When working with re.sub(), consider edge cases like empty inputs, None values, and type mismatches. Python's duck typing means many built-in functions work with any object that implements the required protocol (e.g., __len__ for len(), __iter__ for iteration). This flexibility is a key strength of Python's design philosophy.