python-3.x - 如何从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
解决方案
这是一个解决方案:
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
归功于如何替换除第一个之外的所有事件?.
推荐阅读
- spring - 微服务的依赖注入图
- apache-kafka - Kafka Connect JDBC Sink 连接器:找不到类加载器
- gams-math - 如何将一些参数放入一个 gdx 文件
- unit-testing - 如何为 python3 的 webbrowser 模块编写单元测试?
- testing - 组合/连接 TestCafe 选择器以供重用
- django - DRF 显式排序方向
- apollo-server - visitObject 上的匿名函数?
- php - 通过 Redis Hash 存储和搜索
- resources - EMF 资源负载 - SAXParser 读取地图两次
- java - Landroid/widget/ImageView 类中没有字段 mMaxWidth