【问题标题】:Python .format() not yielding desired outputPython .format() 没有产生所需的输出
【发布时间】:2020-09-07 02:35:12
【问题描述】:

这是我的代码:

form.format(**values).replace('None', 'null')

这是我在代码中传递的表单和值:

values = {'id': 16, 'name': 'PlayStation 3 OS', 'last_modified': '2018-08-16 13:25:46'}
form = %s,%s,%s

当我打印我的代码时。我的代码输出如下:

%s,%s,%s

什么是错误?

【问题讨论】:

  • .format() 无法识别 %s 或任何其他 % 占位符。你应该使用{}
  • @DYZ 它仍然显示相同。请检查您的编译器并帮助我先生。我这样做了
  • print('{},{},{}'.format(**values).replace('None', 'null'),'ccc') IndexError: Replacement index 0 out of位置参数元组的范围
  • .format() 也不适用于字典。您混淆了几种不兼容的格式化方法。

标签: python-3.x


【解决方案1】:

使用 form='{} {} {}' 而不是 %s

values = {'id': 16, 'name': 'PlayStation 3 OS', 'last_modified': '2018-08-16 13:25:46'}

form = "{} {} {}"

print(form.format(values['id'],values['name'],values['last_modified']))

【讨论】:

  • 它显示 print('{},{},{}'.format(**values).replace('None', 'null'),'ccc') IndexError: Replacement index 0超出位置参数元组的范围
  • 添加后试一下代码---replace('None', 'null')
  • 我试过它不工作你可以检查在线翻译先生。请帮助我。
  • 你能简单地说一下你想在这段代码中实现什么吗?你想用正确的格式打印字典中的值吗?
  • print("{:s},{:s},{:s}.".format(*values)) 用你的代码试试这个
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多