Folder or truncated string based on fixed length
There is currently code that looks something like this:
print '{: <5}'.format('test')
This will contain my string c ' '
if it is less than 5 characters. If the string is more than 5 characters long, I need the string to be truncated.
Without explicitly checking the length of my string before formatting it, is there a better way to shim if it's less than a fixed length, or truncated if it's greater than a fixed length?
+3
source to share
2 answers
You can use 5.5
to combine truncation and padding so that the output is always five in length:
'{:5.5}'.format('testsdf')
# 'tests'
'{:5.5}'.format('test')
# 'test '
+6
source to share