简体   繁体   中英

Remove every second comma from string (python)

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM