-4

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.
2
  • I'll edit and post what I tried then and why it failed. I've read those docs about a dozen times now and I'm just not seeing what I need.
    – WhiteleyJ
    Dec 31, 2012 at 16:22
  • I think the last examples were meant to write "{0:<15}"
    – kon psych
    Mar 18, 2020 at 16:05

1 Answer 1

2

For the numbers:

>>> for n in (25, 100, 1234567890):
        print('{:0>8}'.format(n)[-8:])

00000025
00000100
34567890

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:

>>> 'Spams spam and spam'[:15]
'Spams spam and '
>>> 'viking inc'[:15]
'viking inc'

If you want to pad it again—which you didn’t in your example—then you can use format again:

>>> '{:<15}'.format('Spams spam and spam'[:15])
'Spams spam and '
>>> '{:<15}'.format('viking inc'[:15])
'viking inc     '
1
  • the .format(n)[-8] thing was the mental kick that I needed to make the connection. For some reason I tried slicing like that and gave it up as impossible.
    – WhiteleyJ
    Dec 31, 2012 at 16:27

Not the answer you're looking for? Browse other questions tagged or ask your own question.