Python中的元组格式?

问题描述 投票:0回答:1

我很抱歉标题是否以任何方式引起误导。我目前在程序方面遇到问题。我的第一个函数将字符串作为输入并将其转换为元组。我的第二个功能是在带有固定宽度字段的表中修改和打印元组,这就是我遇到的麻烦。这是我尝试过的:

string = 'abc acb bac bca 100000'

def function_one(string):
    modify_one = string.split(' ')
    my_tuple = (modify_one[3], modify_one[2], 
    modify_one[4], modify_one[1], modify_one[0])
    print(my_tuple)

def function_two(my_tuple):

    print(my_tuple)
    formatted = u'{:<15} {:<15} {:<8} {:<5} {:<5}'.format(my_tuple[3], '|', my_tuple[2], '|', my_tuple[4], '|', my_tuple[1], '|', my_tuple[0])
    print(formatted)

function_two(my_tuple)

function_one(string)

我的输出(仅打印5之3):

('bca', 'bac', '100000', 'acb', 'abc')
('bca', 'bac', '100000', 'acb', 'abc')
acb             |               100000   |     abc  

重要!我知道,只有一个字符串不能像表一样。最初,我被要求在程序中插入一个文本文件,到目前为止我还没有弄清楚该怎么做。我使用一个字符串只是为了确保功能正常工作。预先谢谢你。

python string function tuples
1个回答
2
投票

您的格式参数包含分隔符,但是格式字符串中没有足够的格式说明符。

您可能是说

'{:<15} | {:<15} | {:<8} | {:<5} | {:<5}'.format(my_tuple[3], my_tuple[2], my_tuple[4], my_tuple[1], my_tuple[0])

也可以写成如下,以受益于以下事实:可以在位置上解压缩参数,格式说明符可以指定参数的索引:

'{3:<15} | {2:<15} | {4:<8} | {1:<5} | {0:<5}'.format(*my_tuple)
© www.soinside.com 2019 - 2024. All rights reserved.