Python字符串填充

2024-05-14 14:46:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从一个元组输出一个字符串,每个元素之间的宽度不同。在

以下是我目前使用的代码:

b = tuple3[3] + ', ' + tuple3[4] + '          ' + tuple3[0] + ' ' 
+ tuple3[2] + '          ' + '£' + tuple3[1]

print(b)

例如,我输入以下几行文本:

^{pr2}$

输出如下:

Smith, John M          12344 Test          £30000
Jones, Billy          12345 Teso          £1312

我怎样才能使填充物与3个部件之间的间距保持一致?在

另外,当我直接从文本文件输入这些字符串时,我收到的输出是:

  Smith
, John M          12344 Test          £30000
Jones, Billy          12345 Teso          £1312

我如何解决这个问题?在

非常感谢。在


Tags: 字符串代码test文本元素宽度john元组
1条回答
网友
1楼 · 发布于 2024-05-14 14:46:49

字符串格式化到救援!在

lines_of_text = [
    (12345, 1312,  'Teso', 'Billy',  'Jones'),
    (12344, 30000, 'Test', 'John M', 'Smith')
]

for mytuple in lines_of_text:
    name = '{}, {}'.format(mytuple[4], mytuple[3])
    value = '£' + str(mytuple[1])
    print('{name:<20} {id:>8} {test:<12} {value:>8}'.format(
        name=name, id=mytuple[0], test=mytuple[2], value=value)
    )

结果

^{pr2}$

相关问题 更多 >

    热门问题