【问题标题】:How can I pad an fstring with dictionary values in [closed]如何在 [关闭] 中使用字典值填充 fstring
【发布时间】:2022-01-13 12:54:45
【问题描述】:

我可以将 fstring 与字典一起使用:

mydict = {'foo': 'py', 'bar': 'thon'}
print(f"I am using {mydict['foo']}{mydict['bar']}")
> I am using python

我也可以填充字符串:

f"{'Foo': <16} Bar"
>'Foo              Bar'

我希望能够在我的 fstring 中填充来自我的字典的字符串。

我试过了:

f"{{mydict['foo']}: <16} {mydict['bar']}"

这里的错误是:

文件“”,第 1 行
SyntaxError: f-string: single '}' is not allowed

这可能吗,还是我必须先将填充字符串添加到我的字典中才能使用?

【问题讨论】:

  • f"{mydict['foo']: &lt;16} {mydict['bar']}"…?!

标签: python dictionary padding f-string


【解决方案1】:

内部的 {} 是多余的:

mydict = {'foo': 'py', 'bar': 'thon'}
f"{mydict['foo']: <16} {mydict['bar']}"

有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 2020-05-30
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    • 2020-11-04
    • 2020-10-28
    相关资源
    最近更新 更多