Python Forum
re.sub(r"\W", v, s) vs. re.sub(r"\W+", v, s)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
re.sub(r"\W", v, s) vs. re.sub(r"\W+", v, s)
#1
Is there any difference between re.sub(r"\W", v, s) and re.sub(r"\W+", v, s)? Won't they both equally replace all non-alphanumeric characters in s with v?
Reply
#2
Yes, there's a difference because each replacement is done separately.

The first example will replace every non-word character (\W) with your replacement string.

>>> re.sub(r"\W", "X", "Hello, there!")
'HelloXXthereX'
The second will replace every group of consecutive non-word characters with a single instance of the replacement string.

>>> re.sub(r"\W+", "X", "Hello, there!")
'HelloXthereX'
Reply


Forum Jump:

User Panel Messages

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