Fixed width string formatting in python
by mikez0r on Feb.25, 2009, under Nerd, Uncategorized
I wanted to make a nice, pretty text file from some log info, but python didn’t want to cooperate with string formatting.
I was trying something like this:
f=open(‘file’,'w’)
f.write(‘%-10s’ %string)
At the interactive prompt, the equivalent print command would give the desired result.
I got it to work by replacing f.write() with
print >> f, mystring.ljust(10)
This code has the same net result of printing to the file, but it actually does the spacing properly.
This thread gave me the hint I needed, though it looks like the poor guy never resolved his issue – he should have tried the print suggestion.
http://bytes.com/groups/python/25205-using-string-ljust-try-hold-fixed-width#links
1 Trackback or Pingback for this entry
December 21st, 2011 on 07:34
[...] printf http://t3hmikez0r.com/2009/02/25/fixed-width-string-formatting-in-python/ Fixed width string formatting in [...]