Special characters inside square brackets in Python
Special characters inside [ ] become normal characters, meaning they don't need to be escaped with a backslash.
Example
In this example, the search pattern looks like this: between the x's any letter 'a', 'b', 'c', or a period:
txt = 'xax xbx xcx xdx x.x x@x'
res = re.sub('x[abc.]x', '!', txt)
print(res)
Result of code execution:
'! ! ! xdx ! x@x'
Example
In this example, the search template looks like this: between the x's any small Latin letter or a dot:
txt = 'xax xbx xcx x@x'
res = re.sub('x[a-z.]x', '!', txt)
print(res)
Result of code execution:
'! ! ! x@x'
Practical tasks
Given a string:
txt = 'aba aea aca aza axa a.a a+a a*a'
Write a regular expression that will find the strings 'a.a', 'a+a', 'a*a', without affecting the rest.
Given a string:
txt = 'xaz x.z x3z x@z x$z xrz'
Write a regular expression that will find strings with the pattern: letter 'x', then NOT a dot, NOT a dog, and NOT a dollar, and then a letter 'z'.