删除字符串中的每个逗号,除了最后一个带有python

发布于 2025-01-22 13:37:21 字数 255 浏览 1 评论 0原文

我有那些字符串,

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

不弃不离 2025-01-29 13:37:21

这是str.replace的解决方案。 替换函数接受第三个参数,该参数指定替换的最大事件数量。因此,您可以传递比字符串中出现数量的数字(your_string.count(“,”,“”) - 1)。

>>> s1 = "1,395,54"
>>> s1.replace(",", "", s1.count(",") - 1)
'1395,54'
>>> s2 = "1,5,6,75"
>>> s2.replace(",", "", s2.count(",") - 1)
'156,75'

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).

>>> s1 = "1,395,54"
>>> s1.replace(",", "", s1.count(",") - 1)
'1395,54'
>>> s2 = "1,5,6,75"
>>> s2.replace(",", "", s2.count(",") - 1)
'156,75'
放飞的风筝 2025-01-29 13:37:21

您可以用f -strings拆分并重新加入 -

*rest, last = s1.split(',')
f'{"".join(rest)},{last}'

您可以将它们组合到一个衬里 -

''。join(s1.split(',',',')[: - 1]) +” ,“ + s1.split(',')[ - 1]

You could split and rejoin with f-strings -

*rest, last = s1.split(',')
f'{"".join(rest)},{last}'

You can combine those into a one liner -

''.join(s1.split(',')[:-1]) + "," + s1.split(',')[-1]

星星的軌跡 2025-01-29 13:37:21

您可能还会使用一种模式,断言右侧有一个逗号,只有数字介于两者之间:

import re

s1 = "1,395,54"
s2 = "1,5,6,75"

pattern = r",(?=\d*,)"

print(re.sub(pattern, "", s1))  # 1395,54
print(re.sub(pattern, "", s2))  # 156,75

更广泛的变体接受除了之间的逗号以外的任何char:

,(?=[^,]*,)

You might also use a pattern asserting that there is a comma present to the right with only digits in between:

import re

s1 = "1,395,54"
s2 = "1,5,6,75"

pattern = r",(?=\d*,)"

print(re.sub(pattern, "", s1))  # 1395,54
print(re.sub(pattern, "", s2))  # 156,75

The broader variant accepting any char except a comma inbetween:

,(?=[^,]*,)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文