Python格式化的字符串

时间:2019-07-19 13:36:19

标签: python python-3.x string io python-textprocessing

程序1:

print('{:-10}9'.format(12345))
print('{:-10}9'.format(8973955))

程序1的输出

     123459
   89739559

程序2:

print('{:10}9'.format(12345))
print('{:10}9'.format(8973955))

程序2的输出

     123459
   89739559

两个程序之间只有一个区别。在第一个程序中,我使用-10来增加缩进量。在第二个程序中,我使用10作为额外的缩进。 -10和10都在左侧缩进。但是我想在右侧进行缩进,以便产生如下输出:

12345     9
8973955   9

如何使用格式化的字符串文字在右侧缩进

1 个答案:

答案 0 :(得分:3)

指定对齐方式的方向(对齐方式选项):

print('{:<10}9'.format(12345))
print('{:<10}9'.format(8973955))

输出:

12345     9
8973955   9

https://docs.python.org/3.4/library/string.html#format-specification-mini-language