用 % 格式替换占位符时出现类型错误
尝试使用 % 格式替换 {0} 等占位符时,开发人员可能会遇到以下情况错误:“类型错误:并非所有参数在字符串格式化期间都已转换。”此错误源于格式不正确,特别是由于旧式 % 格式和新式 {} 格式之间的混淆所致。
旧式 % 格式使用 %d 等占位符进行格式设置,如下例所示:
'It will cost $%d dollars.' % 95
但是,当使用多个值时,它们必须作为元组提供:
"'%s' is longer than '%s'" % (name1, name2)
另一方面,新式 {} 格式使用 {} 等占位符和 .format 方法。避免混合这两种风格至关重要。如果模板字符串包含 {} 占位符,则应使用 .format,而不是 %.
# Correct: 'It will cost ${0} dollars.'.format(95) "'{0}' is longer than '{1}'".format(name1, name2) # Incorrect (Do not mix % and {}): 'It will cost ${0} dollars.' % 95 "'%0' is longer than '%1'" % (name1, name2)
通过遵守这些格式指南,开发人员可以解决“TypeError: not all argument conversion during string formatting”错误和格式他们的字符串正确。
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3