Reputation: 9235
In Python 3, how can I set a string to print in a set amount of characters no matter the length, like how you can do {:6.2f}
for floats. Set it so that it will take 20 characters, even if there isn't 20 characters.
Upvotes: 0
Views: 613
Reputation: 353
You can use %20s syntax:
"%20s" % "12345" # => ' 12345'
For left justification use %-20s:
"%-20s" % "12345" # => '12345 '
For limitation string length use %20.20s syntax, where first number is min string length and second number is max.
"%20.20s" % ("12345" * 5) # => '12345123451234512345'
Upvotes: 0
Reputation: 799530
Exactly the same way.
>>> '{:20}'.format('1234567890')
'1234567890 '
If you need to limit the length then specify the precision as well.
>>> '{:20}'.format('123456789012345678901234567890')
'123456789012345678901234567890'
>>> '{:20.20}'.format('123456789012345678901234567890')
'12345678901234567890'
Upvotes: 1