← How-To Guides How-To How to replace text with regex Use re.sub(pattern, repl, string). Use a callable as repl for dynamic replacement. sub re.sub replaces all matches. import re s = re.sub(r'\s+', '-', 'a b c') # 'a-b-c'