python - 格式化字符串

标签 python string python-2.7 formatting

我想以一种性感的对齐方式打印一个字符串,但我看不出我做错了什么?

我想实现这个:

15     OBJECT (7)      Content Placeholder 5
17     BODY (2)        Text Placeholder 1
18     BODY (2)        Text Placeholder 2
23     OBJECT (7)      Content Placeholder 3
24     PICTURE (18)    Picture Placeholder 4
25     BODY (2)        Text Placeholder 6

我的代码:

for shape in slide.placeholders:
    print '{0:<5}  {1}      {2:<5}'.format(shape.placeholder_format.idx, 
                                           shape.placeholder_format.type, 
                                           shape.name)

但这就是我得到的

15     OBJECT (7)      Content Placeholder 5
17     BODY (2)      Text Placeholder 1
18     BODY (2)      Text Placeholder 2
23     OBJECT (7)      Content Placeholder 3
24     PICTURE (18)      Picture Placeholder 4
25     BODY (2)      Text Placeholder 6

仅供引用 - 这样做: print '{0:<5} {1:<15} {2:<5}'.format(...)

给了我这个:

15    7               Content Placeholder 5
17    2               Text Placeholder 1
18    2               Text Placeholder 2
23    7               Content Placeholder 3
24    18              Picture Placeholder 4
25    2               Text Placeholder 6

它有点侵 eclipse 我的中间文本栏?

最佳答案

您需要将第二个元素定义为左对齐,如下所示

print '{0:<5} {1:<15} {2}'.format(...)

这里,你说第一列应该左对齐,宽度为5,第二项也应该左对齐,宽度为15。

关于python - 格式化字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29235718/

相关文章:

java - 我无法解释 System.in.read() 行为

python-2.7 - 当 Airflow 为initdb时,ImportError:无法导入名称HiveOperator

python - 如何使用 python 2.7 导出带标题的 CSV 文件

python - 为什么 is_integer() 方法不起作用?

python - 如何找到特定python模块对应的文件?

c++ - 为什么 strlen (..) 不期望 const char* const str 而不是 const char*

python - 如何在 Python 函数中返回左值?

python - Selenium (with python) 如何修改元素的 css 样式

python - 使用线程在后台加载内容

asp.net-mvc - 使用 Razor View 引擎 - 如何将十进制值格式化为逗号和两位小数?