删除字符串中的每个逗号,除了最后一个带有python
我有那些字符串,
s1 = "1,395,54"
s2 = "1,5,6,75"
除了最后获得以下字符串外,我想要所有逗号:
s1 = "1395,54"
s2 = "156,75"
解决这个简单问题的最有效方法是什么?
I have those strings
s1 = "1,395,54"
s2 = "1,5,6,75"
I would like all commas except the last to obtain the following strings:
s1 = "1395,54"
s2 = "156,75"
What is the most efficient way to solve this simple problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是
str.replace
的解决方案。替换
函数接受第三个参数,该参数指定替换的最大事件数量。因此,您可以传递比字符串中,
出现数量的数字(your_string.count(“,”,“”) - 1
)。Here is the solution with
str.replace
.replace
function accepts a third argument which specifies Maximum number of occurrences to replace. So you can pass a number which is one less than the number of occurrences of,
in your string(your_string.count(",") - 1
).您可以用
f -strings
拆分并重新加入 -您可以将它们组合到一个衬里 -
''。join(s1.split(',',',')[: - 1]) +” ,“ + s1.split(',')[ - 1]
You could split and rejoin with
f-strings
-You can combine those into a one liner -
''.join(s1.split(',')[:-1]) + "," + s1.split(',')[-1]
您可能还会使用一种模式,断言右侧有一个逗号,只有数字介于两者之间:
更广泛的变体接受除了之间的逗号以外的任何char:
You might also use a pattern asserting that there is a comma present to the right with only digits in between:
The broader variant accepting any char except a comma inbetween: