Add Padding Around String

Goal

This post aims to introduce how to add padding around string.

Reference:

Create a string and number

In [6]:
string = 'abc_def'
num = 10

Add padding by " "(space) or other character

There is a method for string, called ljust

S.ljust(width[, fillchar]) -> str
In [3]:
string.ljust(10)
Out[3]:
'abc_def   '
In [5]:
string.ljust(10, 'a')
Out[5]:
'abc_defaaa'

Add zero padding to numbers

In [10]:
# the chaaracter after ":" is the one used for padding
'{:010}'.format(num)
Out[10]:
'0000000010'
In [13]:
# python >= 3.6 
# the character after ":" is the one used for padding
f'{num:010}'
Out[13]:
'0000000010'

Comments

Comments powered by Disqus