【问题标题】:Replace placeholder with format function in python3用python3中的格式函数替换占位符
【发布时间】:2020-04-04 22:12:18
【问题描述】:
python3
width=4
' {:>%d} ' %width
' {:>4} '
width=8
' {:>%d} ' %width
' {:>8} '

我想用python3中的format函数得到上面的效果。

width=4
' {:>%d} '.format(width)
' {:>%{0}} '.format(width)    

没有一个可以通过格式化函数获得' {:>4} '

' :>%{0} '.format(width)
' :>%4 '

如何通过格式化函数获取字符串' {:>4} '而不是' :>%4 '
我不喜欢这种表达方式:

>>> '{' + ' :>%{0} '.format(width) + '}'
'{ :>%4 }'

【问题讨论】:

  • 这有点像 XY 问题,因为您自己生成的字符串被用作字符串格式。你在用那个结果字符串做什么?可能有更好的方法来获得最终结果

标签: python-3.x format placeholder


【解决方案1】:
>>> '{{ :>%{0} }} '.format(width)
'{ :>%4 } '

【讨论】:

    猜你喜欢
    • 2023-04-06
    • 1970-01-01
    • 2013-08-13
    • 2017-09-11
    • 2013-01-24
    • 2013-04-08
    • 2018-04-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多