【问题标题】:python string format: how can I combine width and dictionary elements using str.format() [duplicate]python字符串格式:如何使用str.format()组合宽度和字典元素[重复]
【发布时间】:2019-11-11 10:05:11
【问题描述】:

我正在尝试使用较新的 str.format() 格式化字典并指定元素的宽度:

>>> record = { 'name': 'Donald Trump', 'age': 12 }
>>> print "{name} {age}".format(**record)
Donald Trump 12
>>> # how would I set width for the name field to accommodate longer names

如何结合使用字典属性访问格式如宽度控制?

【问题讨论】:

  • 您要求 3 个元素。一个是在: 之前“静默”。只需更改为:print "{name:>30} {age}".format(**record)
  • 这就是答案,但 sagism 不能接受评论 :)
  • 阅读这个pyformat summary,它有很多不同的格式选项和有用的解释

标签: python


【解决方案1】:

正确的语法如下:

In [31]: print("{name} {age}".format(**record))                                                                                                                                                                                                               
Donald Trump 12

In [32]: print("{name:>30} {age}".format(**record))                                                                                                                                                                                                           
                  Donald Trump 12

In [33]: print("{name:30} {age}".format(**record))                                                                                                                                                                                                            
Donald Trump                   12

请注意,我使用的是 Python 3.7,如果您使用的是 Pythonprint 方法中删除括号。

来自Python docs

对齐 ::= "" | “=” | "^"

>>> '{:<30}'.format('left aligned')
'left aligned                  '
>>> '{:>30}'.format('right aligned')
'                 right aligned'
>>> '{:^30}'.format('centered')
'           centered

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-18
    • 1970-01-01
    • 2012-01-15
    • 2015-11-09
    • 2021-12-21
    相关资源
    最近更新 更多