formatting strings to have the same width

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Sat Mar 17 19:45:18 EDT 2007


On Sat, 17 Mar 2007 16:07:44 -0700, spohle wrote:

> hi,
> 
> i got random strings and wanna attach a " |  " at the end. now if i
> print them i want the | to always be underneath each other. example
> code:
> 
> foo = ["aaa", "1232"]
> for each in foo:
> 
> print foo[0].center(10, " ") + " | "
> foo2 = "1232"
> print foo2.center(10, " ") + " | "
> 
> even though i define a constant width on the strings the | don't show
> up underneath each other.
> any ideas ?

Three possibilities:

(1) Your code is fine, but whatever you are using to display the strings
is wrong because it is using the wrong sort of font.

What font are you using? If it is a proportional font, e.g. Times New
Roman, then each different character is a different width, and counting
characters is not likely to result in equal widths.

e.g. compare these two lines:

mw mw mw mw mw |
il il il il il |

If the vertical bars line up, you're (probably) using a fixed-width font
like Courier. If they're not, you're (probably) using a proportional font
like Ariel or Times.


(2) Your code is fine, but your data is bad. 

You are centering your strings with a width of ten. Is it possible that
some of the strings you are passing into the are longer than ten
characters? If so, you'll get funny results, because str.center() will
never shorten the string you pass it.


(3) You code in Python like you write in English: poorly with lots of
errors. "Wanna" isn't a word (unless you're trying to be funny), and
capitalization is the difference between:

I helped my Uncle Jack off a horse

and 

I helped my uncle jack off a horse.

After fixing your indentation error, your example code works perfectly
for me. Perhaps your real code is different, and part of the difference
causes the problem? For instance, your example code seems to do something
unlikely to be useful:

foo = ["aaa", "1232"]
for each in foo:
    print foo[0].center(10, " ") + " | "

That prints the FIRST item each time around the loop, instead of each item.

Also, you don't need the second argument to center. By default, space is
used as a fill character.



-- 
Steven.




More information about the Python-list mailing list