1

I would like to remove every second occurence of a comma in my string but starting from the second comma. My string: "30, 20, 40, 50" and I would like my result to be: "30 20, 40 50" So far I have been using regular expressions to try and achieve this by the following reg sub: myString = re.sub('(,[^,])*,', r'\1', myString) but this results in: "30, 20 40, 50". I hope someone can help me out here.

2
  • I got "30 20 40 50" for this expression and not "30, 20 40, 50" on my machine. Commented Apr 13, 2021 at 8:10
  • Please stop editing the thread with mistakes. Leave it as is and move on, thank you. Commented Apr 14, 2021 at 13:17

2 Answers 2

5

You can group the non-comma characters and the optional following comma for preservation instead:

myString = re.sub(',([^,]*,?)', r'\1', myString)

Demo: https://replit.com/@blhsing/EminentWholeOctagons

Sign up to request clarification or add additional context in comments.

1 Comment

Will mark your response as the solution as it managed to do the same. Thanks.
0

Thanks to those that responded. My own solution meanwhile ended up being: myString = re.sub(',([^,]*[,]*)', r'\1', myString)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.