简体   繁体   English

从字符串中删除每隔一个逗号(python)

[英]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".我的字符串:“30, 20, 40, 50”,我希望我的结果是:“30 20, 40 50” 到目前为止,我一直在使用正则表达式来尝试通过以下 reg sub 实现这一点: myString = re.sub('(,[^,])*,', r'\1', myString)但这会导致:“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演示: https://replit.com/@blhsing/EminentWholeOctagons

Thanks to those that responded.感谢那些做出回应的人。 My own solution meanwhile ended up being: myString = re.sub(',([^,]*[,]*)', r'\1', myString)同时我自己的解决方案最终是: myString = re.sub(',([^,]*[,]*)', r'\1', myString)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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