首页 > 解决方案 > 如何从python中的字符串中删除一些点

问题描述

我正在从表中提取一个 int,但令人惊讶的是,它是一个带有多个句号的字符串。这就是我得到的:

p = '23.4565.90'

我想删除最后一个点,但在转换为 in 时保留第一个点。如果我这样做

print (p.replace('.',''))

所有点都被删除了我该怎么做。

N/B 尝试了很长的路要走

p = '88.909.90000.0'
pp = p.replace('.','')
ppp = list(''.join(pp))
ppp.insert(2, '.')
print (''.join(ppp))

但是发现有些数字是 170.53609.45,在这个例子中,我最终会得到 17.05360945 而不是 170.5360945

标签: python-3.x

解决方案


这是一个解决方案:

p = '23.4565.90'

def rreplace(s, old, new, occurrence):
    li = s.rsplit(old, occurrence)
    return new.join(li)

# First arg is the string
# Second arg is what you want to replace
# Third is what you want to replace it with
# Fourth is how many of them you want to replace starting from the right.
#    which in our case is all but the first '.'
d = rreplace(p, '.', '', p.count('.') - 1) 
print(d)

>>> 23.456590

归功于如何替换除第一个之外的所有事件?.


推荐阅读