Python - 第二次复制一个字符时删除它 [英] Python - Remove a character the second time it is duplicated

查看:56
本文介绍了Python - 第二次复制一个字符时删除它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从字符串中删除一个,"(逗号),但只有第二次出现逗号,因为它需要采用正确的格式进行反向地理编码...

例如,我在 python 中有以下字符串:

43,14,3085

我将如何将其转换为以下格式:

43,143085

我尝试过使用 regex 和 str.split() 但还没有达到效果..

解决方案

如果您确定该字符串只包含两个逗号,而您想删除最后一个,您可以使用 rsplitjoin:

<预><代码>>>>s = '43,14,3085'>>>''.join(s.rsplit(',', 1))'43,143085'

在上面的 rsplit 中,从作为第二个参数给出的结束次数开始拆分:

<预><代码>>>>零件 = s.rsplit(',', 1)>>>部分['43,14', '3085']

然后使用join将各个部分组合在一起:

<预><代码>>>>''.join(部分)'43,143085'

I'm looking to remove a ',' (comma) from a string, but only the second time the comma occurs as it needs to be in the correct format for reverse geocoding...

As an example I have the following string in python:

43,14,3085

How would I convert it to the following format:

43,143085

I have tried using regex and str.split() but have not achieved result yet..

解决方案

If you're sure that string only contains two commas and you want to remove the last one you can use rsplit with join:

>>> s = '43,14,3085'
>>> ''.join(s.rsplit(',', 1))
'43,143085'

In above rsplit splits starting from the end number of times given as a second parameter:

>>> parts = s.rsplit(',', 1)
>>> parts
['43,14', '3085']

Then join is used to combine the parts together:

>>> ''.join(parts)
'43,143085'

这篇关于Python - 第二次复制一个字符时删除它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆