【问题标题】:Using Python's Format Specification Mini-Language to print spaces with variables [duplicate]使用 Python 的 Format Specification Mini-Language 打印带有变量的空格 [重复]
【发布时间】:2020-03-20 03:09:42
【问题描述】:

我尝试使用 Specification Mini-Language 和变量来打印空格。

例如:

而不是这个

print('{:>10}'.format('hello'))

我想这样做:

i = 10
print('{:>i}'.format('hello'))

我得到这个错误:

ValueError:“str”类型的对象的未知格式代码“i”

【问题讨论】:

    标签: python


    【解决方案1】:

    i 放在括号中,并将其添加到格式参数中,如下所示:

    i = 10
    print('{:>{i}}'.format('hello', i=i))
    #      hello
    

    【讨论】:

      【解决方案2】:

      可以这样:

      print(('{:>' + str(i) +'}').format('hello'))
      

      【讨论】:

        【解决方案3】:

        您可以像这样创建自己的格式字符串:

        i = 10
        format_string = '{:>' + str(i) + '}'
        print(format_string .format('hello'))
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-04-24
          • 1970-01-01
          • 2011-03-16
          • 2017-03-08
          相关资源
          最近更新 更多