On this page
  1. re.sub
  2. Import
  3. Signature & Overview
  4. Usage
  5. Gotchas
  6. REPL Inspect

re.sub

Prev: re.split | Up: re | Next: re.subn
Rel: re.compile, re.error, re.escape, re.findall
Ref: docs.python.org — re.sub
Tags: #public #python3 #stdlib #re


Import

import re
from re import sub

Signature & Overview

re.sub(pattern, repl, string, count=0, flags=0)

Return the string obtained by replacing the leftmost non-overlapping occurrences of the pattern in string by the replacement repl. repl can be either a string or a callable;

Usage

import re

assert re.sub(r"\s+", "-", "hello   world\t!") == "hello-world-!"
# Pass a function for dynamic replacements
doubled = re.sub(r"\d+", lambda m: str(int(m.group()) * 2), "a=3 b=10")
assert doubled == "a=6 b=20"

Gotchas

REPL Inspect

from re import sub
help(sub)

Linked from

Related notes