Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pad or truncate string based on fixed length

Currently have code that looks something like;

print '{: <5}'.format('test')

This will pad my string with ' ' if it is less than 5 characters. If the string is more than 5 characters, I'd need the string to be truncated.

Without explicitly checking the length of my string before formatting it, is there a better way to pad if less than fixed length or truncate if greater than fixed length?

like image 791
etm124 Avatar asked May 12 '17 13:05

etm124


2 Answers

You can use 5.5 to combine truncating and padding so that the output will always be of length of five:

'{:5.5}'.format('testsdf')
# 'tests'

'{:5.5}'.format('test')
# 'test '
like image 186
Psidom Avatar answered Sep 21 '22 18:09

Psidom


You could use str.ljust and slice the string:

>>> 'testsdf'.ljust(5)[:5]
'tests'
>>> 'test'.ljust(5)[:5]
'test '
like image 40
Chris_Rands Avatar answered Sep 19 '22 18:09

Chris_Rands