Replacing
suggest changeReplacements can be made on strings using re.sub.
Replacing strings
re.sub(r"t[0-9][0-9]", "foo", "my name t13 is t44 what t99 ever t44")
# Out: 'my name foo is foo what foo ever foo'
Using group references
Replacements with a small number of groups can be made as follows:
re.sub(r"t([0-9])([0-9])", r"t\2\1", "t13 t19 t81 t25")
# Out: 't31 t91 t18 t52'
A replacement such as \10 is group 10, not group 1 followed by a literal 0 (docs). With only two groups, re.sub raises re.error (invalid group reference 10). Use the \g<i> notation when the group number would otherwise run into the following digits:
re.sub(r"t([0-9])([0-9])", r"t\g<2>\g<1>", "t13 t19 t81 t25")
# Out: 't31 t91 t18 t52'
Using a replacement function
items = ["zero", "one", "two"]
re.sub(r"a\[([0-3])\]", lambda match: items[int(match.group(1))], "Items: a[0], a[1], something, a[2]")
# Out: 'Items: zero, one, something, two'
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents