Diversity of format length

Hi,

I am trying to format many string with fixed length. Please check the following code.

However, I have to change the length of the fixed length like the second piece of code.

Is the second piece of code correct?
what is the correct syntax?


s = ''
s += '{:>16s}'.format('csdfac')
s += '{:>16s}'.format('cdfasdc')
s += '{:>16s}'.format('cdfdsc')
s += '{:>16s}'.format('cdfasdc')

lent = 16
s = ''
s += '{:>lents}'.format('csdfac')
s += '{:>lents}'.format('cdfasdc')
s += '{:>lents}'.format('cdfdsc')
s += '{:>lents}'.format('cdfasdc')

You need to construct a string which has the value you want, not just toss the variable in there. Since you’re already using format, you could throw it in there. Or you could do it with f-strings.

lent = 16
s = ''
s += '{0:>{1}s}'.format('csdfac', lent)
s += f'{"cdfasdc":>{lent}}'
print(s)

Thank you @BowlOfRed !

Unless your formatting is a bit more complicated than this example, it might make more sense to use the various other string methods such as str.rjust:

lent = 16
s = ''
s += 'csdfac'.rjust(lent)
s += 'cdfasdc'.rjust(lent)
s += 'cdfdsc'.rjust(lent)
s += 'cdfasdc'.rjust(lent)

good example!
Thank you @lvc !