Python Padding Examples: ljust, rjustUse the ljust and rjust methods to add padding to strings. Also use format to specify padding.
Padding. 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.
Ljust and rjust pad strings. They accept one or two arguments. The first argument is the total length of the result string. The second is the padding character.
An example. 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.
Python program that uses ljust, rjust
s = "Paris" # Justify to left, add periods. print(s.ljust(10, ".")) # Justify to right. print(s.rjust(10))
Paris..... Paris
Format. 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.
Here We right-align (rjust) a string with spaces. Then we left-align (ljust) a number with star characters.
Python program that uses format padding
# 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*******
Some notes, loop. 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.
A review. 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.
© 2007-2021 sam allen. see site info on the changelog