I’m looking for a function (hopefully built in) that can create fixed width strings of certian padding and alignments. In my case I have a list of names (among other data) that needs to get put into a fixed with format file.
Example 1: "Spams spam and spam" and "viking inc" both need to be placed into a 15 character fixed width field.
Result: ("Spams spam and ", "viking inc ")
Example 2: A numeric version that converts (25, 100, 1234567890) into an 8 character fixed width string padded with zeros.
Result: ("00000025", "00000100" "34567890") <- Note how dropped the first 2 chars
Acceptable answers may also include calling me an idiot and telling me that there’s something simple for fixed width string handling. Also this should ideally work in python 2.7 and 3.3 (our company is currently on 2.7, but will move to 3.3 soon)
What I’ve tried:
"{0:<30}".format("viking inc") #works
"{0:<30}".format("Spams spam and spam") #does not work, output it too long.
For the numbers:
For the strings, your example is a bit ambigous. If you want to select just the first 15 characters (at most), then just do this:
If you want to pad it again—which you didn’t in your example—then you can use format again: