Python3 - 在字符串格式器参数中使用一个变量 [英] Python3 - Use a variables inside string formatter arguments

查看:283
本文介绍了Python3 - 在字符串格式器参数中使用一个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我打印了一些格式化的列。我想用下面的变量来设置我的.format参数中的长度。

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ name_length = 24
viewers_length = 9

我有
$ b $ ('{0:< 5} {1:< 24} {2:9}'格式('#','channel',' '),end ='')

理想情况下,我希望像


$ b $

  print('{0:< number_length} {1:< name_length} {2:< viewers_length}'。 '#','channel','viewers'),end ='')

我有一个无效的字符串格式化错误。

我已经尝试过%之前的变量和括号,但没有运气。

$ b $ ol <$>
  • 将这些名字包裹在大括号中。和

  • 将宽度作为关键字参数传递给 str.format

  • 例如:

     >>> print({0:> {number_length}}。format(1,number_length = 8))
    1

    您也可以使用字典解包:

     >>> widths = {'number_length':8} 
    >>> print({0:> {number_length}}。format(1,** widths))
    1

    str.format 不会在本地范围中寻找合适的名称;他们必须明确传递。



    对于你的例子,这可以像这样工作:

     >>> widths = {'number_length':5,
    'name_length':24,
    'viewers_length':9}
    >>> template ='{0:< {number_length}} {1:< {name_length}} {2:< {viewers_length}}'
    >>> print(template.format('#','channel','visitors',end ='',** widths))
    #channel visitor
    $ b <注意 end 和任何其他明确的关键字参数必须在 **宽度。)


    I have some formatted columns that I'm printing. I would like to use the following variables to set the lengths in my .format arguments

    number_length = 5
    name_length = 24
    viewers_length = 9
    

    I have

    print('{0:<5}{1:<24}{2:<9}'.format(' #','channel','viewers'), end = '')
    

    Ideally I would like something like

    print('{0:<number_length}{1:<name_length}{2:<viewers_length}'.format(
         ' #','channel','viewers'), end = '')
    

    But this gives me an invalid string formatter error.

    I have tried with % before the variables and parenthesis, but have had no luck.

    解决方案

    You need to:

    1. Wrap the names in braces, too; and
    2. Pass the widths as keyword arguments to str.format.

    For example:

    >>> print("{0:>{number_length}}".format(1, number_length=8))
           1
    

    You can also use dictionary unpacking:

    >>> widths = {'number_length': 8}
    >>> print("{0:>{number_length}}".format(1, **widths))
           1
    

    str.format won't look in the local scope for appropriate names; they must be passed explicitly.

    For your example, this could work like:

    >>> widths = {'number_length': 5,
                  'name_length': 24,
                  'viewers_length': 9}
    >>> template= '{0:<{number_length}}{1:<{name_length}}{2:<{viewers_length}}'
    >>> print(template.format('#', 'channel', 'visitors', end='', **widths))
    #    channel                 visitors
    

    (Note that end, and any other explicit keyword arguments, must come before **widths.)

    这篇关于Python3 - 在字符串格式器参数中使用一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆