Use 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 string. We can left or right-justify a table of text data with padding—we use ljust and rjust.Strings
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.
# Justify to right.
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.format
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")
# Left-align a number in 10 chars.
# ... Pad with a star character.
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.for
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.