⊗pyPmREMSP 57 of 128 menu

Pockets in Python Replacement String

When working with the sub method, if something needs to be put into a pocket in the regular expression, then in the replacement line you can insert the contents of this pocket by writing a double slash \\ and the pocket number. For example, \\1 is the first pocket, \\2 is the second pocket, and so on.

Why is this necessary and how to use it, let's look at examples.

Example

Let's find all the numbers and instead of them insert the same numbers, but in parentheses. To do this, replace all the found numbers with the same numbers, but in parentheses:

txt = '1 23 456 xax' res = re.sub('(\d+)', '(\\1)', txt) print(res)

As a result, the following will be written to the variable:

'(1) (23) (456) xax'

Example

Let's find all the strings that are numbers with x's around them and replace those numbers with the same numbers but with '!' signs around them:

txt = 'x1x x23x x456x xax' res = re.sub('x(\d+)x', '!\\1!', txt) print(res)

As a result, the following will be written to the variable:

'!1! !23! !456! xax'

Example

Let's solve the following problem: given a string 'aaa@bbb ссс@ddd' - letters, then a dog, then letters. We need to swap the letters in the substring 'aaa@bbb' before '@' and after:

txt = 'aaa@bbb sss@ddd' res = re.sub('([a-z]+)@([a-z]+)', '\\2@\\1', txt) print(res)

As a result, the following will be written to the variable:

'bbb@aaa sss@ddd'

Practical tasks

Given a string:

txt = '12 34 56 78'

Swap the digits in all two-digit numbers.

Given a line with a date:

txt = '31.12.2025'

Convert this date to '2025.12.31'.

enru