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.
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.
# 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Aug 28, 2021 (edit).