Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
re.sub not working
#7
(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 work
You 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\x01car
So 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’s raw string notation for regular expression patterns;
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.
Reply


Messages In This Thread
re.sub not working - by Ryokousha - Oct-02-2022, 04:18 AM
RE: re.sub not working - by deanhystad - Oct-02-2022, 04:50 AM
RE: re.sub not working - by Coricoco_fr - Oct-02-2022, 05:42 AM
RE: re.sub not working - by Ryokousha - Oct-02-2022, 07:06 AM
RE: re.sub not working - by Ryokousha - Oct-02-2022, 07:04 AM
RE: re.sub not working - by Pedroski55 - Oct-02-2022, 05:59 AM
RE: re.sub not working - by snippsat - Oct-02-2022, 11:34 AM
RE: re.sub not working - by deanhystad - Oct-02-2022, 03:00 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020