Spaces can be placed to the left or to the right of a Python string. We can left or right-justify a table of text data with padding—we use ljust
and rjust
.
rjust
pad stringsThey accept one or two arguments. The first argument is the total length of the result string
. The second is the padding character.
Here we use ljust
and rjust
. If you specify a number that is too small, ljust
and rjust
do nothing. They return the original string
.
s = "Paris" # Justify to left, add periods. print(s.ljust(10, ".")) # Justify to right. print(s.rjust(10))Paris..... Paris
We can use a pattern with the format built-in to pad strings. Any character can be used. But this style of code is likely harder to read.
rjust
) a string
with spaces. Then we left-align (ljust
) a number with star characters.# Right-align a string in 10 chars. # ... First char in format string is a space. value = format("line 1", " >10s") print(value) # Left-align a number in 10 chars. # ... Pad with a star character. print(format(100, "*<10d")) line 1 100*******
Consider this—a loop could be used to pad strings. This can be needed for more complex requirements. Continue adding characters until the desired length is met.
To pad strings in Python, we can use the format built-in or directly use ljust
and rjust
. Even a loop could be used to insert or append spaces.