对于这种情况,如何在 Python 中使用 replace() 函数?
How to use replace() function in Python for this situation?
情况是我们分别有4,3,4,3。如果我们只想将索引 20 处的 4 修正为 3.5。第三个参数应该是什么?
name = "Land grade 4 year 3 4 members at building 4"
print(name.replace(("4","3.5",?))
我想要的结果->“土地等级4年级3 3.5成员在4号楼”
切片字符串并仅替换您感兴趣的切片,重建字符串。
>>> s = "Land grade 4 year 3 4 members at building 4"
>>> s[0:20]+s[20:24].replace("4","3.5")+s[24:]
'Land grade 4 year 3 3.5 members at building 4'
只有 1 个替换可能稍微好一些,这避免了字符串切片:
>>> s[0:20]+s[20:].replace("4","3.5",1)
'Land grade 4 year 3 3.5 members at building 4'
但是如果您确切地知道要替换的数字在哪里,也许那是因为您可以使用模板字符串来做到这一点。
s = "Land grade 4 year 3 {} members at building 4"
s.format(3.5)
情况是我们分别有4,3,4,3。如果我们只想将索引 20 处的 4 修正为 3.5。第三个参数应该是什么?
name = "Land grade 4 year 3 4 members at building 4"
print(name.replace(("4","3.5",?))
我想要的结果->“土地等级4年级3 3.5成员在4号楼”
切片字符串并仅替换您感兴趣的切片,重建字符串。
>>> s = "Land grade 4 year 3 4 members at building 4"
>>> s[0:20]+s[20:24].replace("4","3.5")+s[24:]
'Land grade 4 year 3 3.5 members at building 4'
只有 1 个替换可能稍微好一些,这避免了字符串切片:
>>> s[0:20]+s[20:].replace("4","3.5",1)
'Land grade 4 year 3 3.5 members at building 4'
但是如果您确切地知道要替换的数字在哪里,也许那是因为您可以使用模板字符串来做到这一点。
s = "Land grade 4 year 3 {} members at building 4"
s.format(3.5)