简体   繁体   中英

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

Additional Info: I am using 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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