简体   繁体   English

Python str.format()方法无法按预期工作

[英]Python str.format() method not working as expected

I am trying to format some output that I'm printing on the screen. 我正在尝试格式化要在屏幕上打印的某些输出。 Here's my code: 这是我的代码:

someString = someList[someIndex] +  '{0:<8}'.format('\t') + someList[someOtherIndex]
print someString

My Expected output: 我的预期输出:

abcdefghi              someOutput
abcde                  someOtherOutput

**OR**
abcdefghi       someOutput
abcde           someOtherOutput

Actual output I get: 我得到的实际输出是:

abcdefghi              someOutput
abcde          someOtherOutput

Q.1: Why am I not getting the expected output? Q.1:为什么我没有得到预期的输出? To be specific, why are the entries in second column mis-aligned? 具体来说,为什么第二列中的条目未对齐?
Q.2: What should I change in my code to get the expected output? Q.2:我应该在代码中进行哪些更改才能获得预期的输出?

Additional Info: I am using Python 2.6 附加信息:我正在使用Python 2.6

Appreciate any help. 感谢任何帮助。

You have to apply the "filling" on the first string you print, such that it "pushes" the second one always to the same point: 您必须在打印的第一个字符串上应用“填充”,以便它始终将“第二个”字符串“推”到同一点:

someString = '{0:<16}{1}'.format(someList[someIndex], someList[someOtherIndex])

Make sure that the filling you require is larger than the longest first word you have to print, though. 但是,请确保所需的填充量大于必须打印的最长的第一个单词。

What you were doing before is simply printing the first word, then printing a '\\t' with filling (which was always the same), and finally the second word. 您之前所做的只是简单地打印第一个单词,然后打印带有填充的“ \\ t”(始终相同),最后打印第二个单词。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM