Oct-02-2022, 11:34 AM
(Oct-02-2022, 07:06 AM)Ryokousha Wrote: Hello, Do you know how can we format string to raw string? I've googled it but that not workYou add
r
(raw string) to the regex pattern,do this always as a habit or can get problems.Example add
car
after new line(\n
).>>> import re >>> >>> s = ' hello world\n' >>> re.sub('(\n)', '\1car', s) ' hello world\x01carSo it fails,now add
r
and it's ok.>>> import re >>> >>> s = ' hello world\n' >>> re.sub(r'(\n)', r'\1car', s) ' hello world\ncar'From regex doc.
Quote:The solution is to use Python’sraw string
notation for regular expressionpatterns
;
backslashes are not handled in any special way in a string literal prefixed with 'r'.
So r"\n" is a two-character string containing '\' and 'n', while "\n" is a one-character string containing a newline.
Usually patterns will be expressed in Python code using this raw string notation.