Un-escaping Python pocket number
Instead of writing a double slash, you can use a special command r
, which is specified before the opening single quotes.
Let's say we have a line:
txt = '1 23 456 xax'
Let's find all the numbers and put them in parentheses. To do this, replace all the numbers we find with the numbers themselves, but in parentheses. And instead of a double slash, use the r
command:
txt = '1 23 456 xax'
res = re.sub('(\d+)', r'(\1)', txt)
print(res)
After executing the code, the following line will be displayed:
'(1) (23) (456) xax'
Given a string:
txt = 'ab cd ef'
Swap the letters in all two-character substrings.
Given a line with a date:
txt = '2025:12:31'
Convert this date to '31-12-2025'
.