0

I have the following string and want to replace the last comma with an "&". I want to do it with Regex, also if it could be done without Regex. This is my example code.

mystring = "a, b, c, d"
print(re.sub(r", \w$", " & ", mystring))  # this gives me "a, b, c &"
                                          # but I want    "a, b, c & d"

Please: Before you press "close" write a comment! There is no duplicate and this should also be reproducible. See the code comments!

kame
  • 20,848
  • 33
  • 104
  • 159
  • Does it have to be regex https://stackoverflow.com/questions/2556108/rreplace-how-to-replace-the-last-occurrence-of-an-expression-in-a-string? – Guy Sep 02 '21 at 11:30
  • @Guy yes! Therefore I added a tag. – kame Sep 02 '21 at 11:33
  • 1
    `"".join(mystring[::-1].replace(",", "& ", 1)[::-1])` just in case you need a solution without `regex` :) – Abdul Niyas P M Sep 02 '21 at 11:35
  • Of course there are duplicates of this, a lot. Here is one, [How to replace only part of the match with python re.sub](https://stackoverflow.com/questions/2763750/how-to-replace-only-part-of-the-match-with-python-re-sub), canonical. – Wiktor Stribiżew Sep 02 '21 at 11:50
  • @WiktorStribiżew Hello Wiktor, but there I don't know how to take the last occurrence. But you said a lot. I don't think there is one with last-occurence. – kame Sep 02 '21 at 11:56
  • There is no problem with your pattern, you just need to capture and backreference the captured text. A common, very well-known issue. – Wiktor Stribiżew Sep 02 '21 at 12:07
  • 1
    You may as well find `,(?!.*,)` and replace with `&`. – JvdV Sep 02 '21 at 12:34

1 Answers1

0

You can use a group () and a backreference \1.

>>> mystring = "a, b, c, d"
>>> print(re.sub(r", (\w)$", r" & \1", mystring))
a, b, c & d

Reference

Wander Nauta
  • 18,832
  • 1
  • 45
  • 62