我正在从表中提取一个 int ,但令人惊讶的是它是一个带有多个句号的字符串。这就是我得到的:
p = '23.4565.90'
Run Code Online (Sandbox Code Playgroud)
我想删除最后一个点,但在转换为 in 时保留第一个点。如果我这样做
print (p.replace('.',''))
Run Code Online (Sandbox Code Playgroud)
所有点都被删除我该怎么做。
N/B 尝试了很长的方法来做到这一点
p = '88.909.90000.0'
pp = p.replace('.','')
ppp = list(''.join(pp))
ppp.insert(2, '.')
print (''.join(ppp))
Run Code Online (Sandbox Code Playgroud)
但发现有些数字是 170.53609.45,在这个例子中,我最终会得到 17.05360945 而不是 170.5360945
这是一个解决方案:
p = '23.4565.90'
def rreplace(string: str, find: str, replace: str, n_occurences: int) -> str:
"""
Given a `string`, `find` and `replace` the first `n_occurences`
found from the right of the string.
"""
temp = string.rsplit(find, n_occurences)
return replace.join(temp)
d = rreplace(string=p, find='.', replace='', n_occurences=p.count('.') - 1)
print(d)
>>> 23.456590
Run Code Online (Sandbox Code Playgroud)
归功于如何替换除第一个之外的所有事件?。
关于什么str.partition?
p = '23.4565.90'
a, b, c = p.partition('.')
print(a + b + c.replace('.', ''))
Run Code Online (Sandbox Code Playgroud)
这将打印:
23.456590
编辑:该方法partition不是separate
| 归档时间: |
|
| 查看次数: |
39940 次 |
| 最近记录: |