Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python字符串填充_Python - Fatal编程技术网

Python字符串填充

Python字符串填充,python,Python,我试图从元组中输出一个字符串,每个元素之间的宽度不同 以下是我目前使用的代码: b = tuple3[3] + ', ' + tuple3[4] + ' ' + tuple3[0] + ' ' + tuple3[2] + ' ' + '£' + tuple3[1] print(b) 例如,我输入以下几行文字: 12345 1312 Teso Billy Jones 12344 30000 Test John M Smith 输出将如下所示: Smith

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

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

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

print(b)
例如,我输入以下几行文字:

12345 1312 Teso Billy Jones
12344 30000 Test John M Smith
输出将如下所示:

Smith, John M          12344 Test          £30000
Jones, Billy          12345 Teso          £1312
如何使填充与3个部分之间的较大间距保持一致

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

  Smith
, John M          12344 Test          £30000
Jones, Billy          12345 Teso          £1312
我如何解决这个问题


非常感谢。

字符串格式设置助您一臂之力

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)
    )

字符串格式的拯救

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)
    )

你输入的“史密斯”在哪里?我看到的都是“Senfkewjnrmith”使用标签怎么样
\t
感谢您对间距进行了排序,但由于某些原因,“Smith”与“code>”仍不在同一行中,John M 12344测试30000”您的输入中“Smith”在哪里?我看到的都是“Senfkewjnrmith”使用标签怎么样<代码>\t感谢您对间距进行了排序,但由于某些原因,“Smith”与“code>”仍不在同一行,John M 12344测试30000英镑。谢谢。我已经缩小了新行随机开始的问题,这是因为我从一个文件中输入字符串,其中
tuple(a.split(“”))
'a'是从文本文件中输入的行。但是,使用此方法,元组以以下格式显示:
('12344','30000','Test','Smith\n','johnm')
。我如何解决这个问题?您是否知道如何使用变量填充进行格式化?像这样:
{name:@Mast:您可以先构建格式字符串,即
fmt=“{{name:{width}}}”.format(width=20)
然后将其传递到print,
print(fmt.format(name=“Billy”)
。谢谢。我已经缩小了新行随机开始的问题,这是因为我从一个带有
元组的文件中输入了字符串(a.split(“”))
'a'是从文本文件输入的行。但是,使用此方法,元组以以下格式显示:
('12344',30000',Test',Smith\n',John M')
。我如何解决此问题?您是否知道如何使用变量填充进行格式设置?如:
'{name:@Mast:您可以首先构建格式字符串,即
fmt=“{{name:{width}}}”.format(width=20)
然后将其传递给print,
print(fmt.format(name=“Billy”)