Python pad string
last modified November 19, 2026 Python 3.15
In this article we show how to pad and align strings in Python.
Padding adds characters to a string until it reaches a given width. Padded strings line up in columns, which is how programs print tables and reports in a terminal. Python strings have four padding methods:
ljustaligns the string to the left and pads the right side,rjustaligns the string to the right and pads the left side,centerpads both sides,zfillpads a number with zeros on the left.
The same alignment is available in format specifications, which are covered in detail in Python f-string.
ljust, rjust, and center
The methods take the width of the result as their first argument and pad the string with spaces.
#!/usr/bin/python
word = 'falcon'
print(f'[{word.ljust(12)}]')
print(f'[{word.rjust(12)}]')
print(f'[{word.center(12)}]')
We put the results in brackets to make the spaces visible. The word has six characters, so each method adds six spaces.
$ python justify.py [falcon ] [ falcon] [ falcon ]
The fill character
The optional second argument is the fill character used instead of the space.
#!/usr/bin/python
title = 'Results'
print(title.center(20, '*'))
print('Total'.ljust(15, '.') + '42')
print('7'.rjust(3, '0'))
try:
title.center(20, '-=')
except TypeError as e:
print('error:', e)
Padding with zeros or dots is common in reports. The fill must be exactly one
character; a longer string raises a TypeError.
$ python fill_char.py ******Results******* Total..........42 007 error: The fill character must be exactly one character long
Longer strings
The padding methods never cut a string. If it is already as wide as requested or wider, it is returned unchanged.
#!/usr/bin/python
word = 'internationalization'
print(f'[{word.ljust(8)}]')
print(f'[{word.ljust(8)[:8]}]')
def fit(s, width):
return s[:width].ljust(width)
for w in ['sky', 'falcon', 'internationalization']:
print(f'[{fit(w, 8)}]')
A long word breaks the layout of a table. To get a fixed width in all cases,
we slice the string to the width first and then pad it. The
fit function does both; slicing is explained in
Python string slicing.
$ python longer.py [internationalization] [internat] [sky ] [falcon ] [internat]
Uneven padding
When the padding cannot be split evenly, one side of a centered string gets an extra character.
#!/usr/bin/python
for width in range(5, 9):
print(width, f'[{"ab".center(width)}]', f'[{"abc".center(width)}]')
print(f'[{"ab":^5}]', f'[{"ab":^7}]')
The center method puts the extra space on the left or on the
right depending on the parity of the width, so the centered strings in the
rows of a table may shift by one column. The ^ format
specification always puts the extra space on the right.
$ python center_odd.py 5 [ ab ] [ abc ] 6 [ ab ] [ abc ] 7 [ ab ] [ abc ] 8 [ ab ] [ abc ] [ ab ] [ ab ]
Padding with zeros
The zfill method pads a numeric string with zeros on the left.
Unlike rjust, it knows about signs.
#!/usr/bin/python
for value in ['42', '-42', '+7', '1234567', '3.5']:
print(f'{value:>8} {value.zfill(6):>8} {value.rjust(6, "0"):>8}')
print(f'{-42:06}', f'{7:03d}')
The zfill method puts the zeros after a leading +
or -, while rjust(6, "0") puts them in front of the
sign. Neither method checks that the string is a number. For numbers rather
than strings, a format specification with a leading zero, such as
06, does the same job.
$ python zfill.py
42 000042 000042
-42 -00042 000-42
+7 +00007 0000+7
1234567 1234567 1234567
3.5 0003.5 0003.5
-00042 007
Format specifications
In f-strings and str.format, the characters <,
>, and ^ align the value within a given width.
#!/usr/bin/python
word = 'falcon'
width = 12
print(f'[{word:<12}]')
print(f'[{word:>12}]')
print(f'[{word:^12}]')
print(f'[{word:*^{width}}]')
print('[{:>{}}]'.format(word, width))
print(f'[{42:<6}] [{42:6}] [{"42":6}]')
The fill character goes before the alignment sign, and the width can come from a variable in a nested replacement field. Without an alignment sign, strings are aligned to the left and numbers to the right, as the last line shows.
$ python format_spec.py [falcon ] [ falcon] [ falcon ] [***falcon***] [ falcon] [42 ] [ 42] [42 ]
Dot leaders
A table of contents connects titles and page numbers with a line of dots, called a dot leader.
#!/usr/bin/python
chapters = [('Introduction', 1), ('Strings', 12), ('Lists and tuples', 38),
('Dictionaries', 57), ('Appendix', 112)]
width = 36
for title, page in chapters:
print(title.ljust(width - 4, '.') + str(page).rjust(4, '.'))
Each line is exactly 36 characters wide. The title is padded to 32 characters and the page number to 4, both with dots, so the page numbers line up on the right.
$ python toc.py Introduction.......................1 Strings...........................12 Lists and tuples..................38 Dictionaries......................57 Appendix.........................112
Aligning columns
To print a table we pad text columns on the right and number columns on the left.
#!/usr/bin/python
products = [('Coffee', 3, 4.5), ('Tea', 12, 2.95),
('Hot chocolate', 1, 3.8), ('Water', 120, 0.9)]
w = max(len(name) for name, _, _ in products)
print('Product'.ljust(w), 'Qty'.rjust(5), 'Price'.rjust(8))
print('-' * (w + 15))
for name, qty, price in products:
print(name.ljust(w), str(qty).rjust(5), f'{price:.2f}'.rjust(8))
The width of the first column is the length of the longest product name. Prices are formatted with two decimal places before padding, so their decimal points line up. The same layout with format specifications is shown in Python f-string.
$ python columns.py Product Qty Price ---------------------------- Coffee 3 4.50 Tea 12 2.95 Hot chocolate 1 3.80 Water 120 0.90
Padding bytes
The bytes type has the same methods. Binary formats often store
strings in fields of fixed size padded with null bytes.
#!/usr/bin/python
names = ['falcon', 'owl', 'kestrel']
records = b''.join(n.encode().ljust(8, b'\x00') for n in names)
print(records)
print(len(records))
for i in range(0, len(records), 8):
print(records[i:i + 8].rstrip(b'\x00').decode())
Each name is encoded and padded to eight bytes with b'\x00'; the
fill must be a bytes object of length one. The records are joined into 24
bytes. Reading them back, we slice eight bytes at a time and strip the
padding.
$ python pad_bytes.py b'falcon\x00\x00owl\x00\x00\x00\x00\x00kestrel\x00' 24 falcon owl kestrel
Wide and combining characters
The padding methods count code points. A terminal, however, shows some characters two columns wide, and others take no column at all.
#!/usr/bin/python
import unicodedata
words = ['sky', 'čaj', '東京', 'Falcon', 'cafe\u0301']
for w in words:
print(f'[{w.ljust(10)}] {len(w)}')
for c in 'a東Fe\u0301':
print(f'U+{ord(c):04X} {unicodedata.east_asian_width(c):2} '
f'{unicodedata.combining(c)}')
The Chinese characters and the fullwidth Latin letters take two columns each,
so their rows stick out. The last word is written with a plain
e and a combining acute accent, which is drawn over the previous
letter; the string has five code points but takes four columns. The
unicodedata.east_asian_width function returns W
(wide) or F (fullwidth) for characters that take two columns,
and combining returns a non-zero value for combining marks.
$ python wide_chars.py [sky ] 3 [čaj ] 3 [東京 ] 2 [Falcon ] 6 [café ] 5 U+0061 Na 0 U+6771 W 0 U+FF26 F 0 U+0065 Na 0 U+0301 A 230
Padding by display width
In the last example we pad strings by the number of columns they occupy in a terminal rather than by their length.
#!/usr/bin/python
import unicodedata
def width(s):
w = 0
for c in s:
if unicodedata.combining(c):
continue
w += 2 if unicodedata.east_asian_width(c) in 'WF' else 1
return w
def ljust_display(s, n, fill=' '):
return s + fill * max(0, n - width(s))
cities = [('Tokyo', '東京', 37.4), ('Seoul', '서울', 9.7),
('Zürich', 'Zu\u0308rich', 0.4), ('Beijing', '北京', 21.9)]
for name, native, pop in cities:
print(f'{name:8}|{ljust_display(native, 8)}|{pop:6.1f}')
The width function counts two columns for wide characters and
none for combining marks. The ljust_display function adds as many
fill characters as the string lacks to the requested width. The native names
now line up, including the decomposed Zürich. The rules are a
simplification; the third-party wcwidth library also handles
emoji and control characters.
$ python display_width.py Tokyo |東京 | 37.4 Seoul |서울 | 9.7 Zürich |Zürich | 0.4 Beijing |北京 | 21.9
Source
str.ljust – Python documentation
Format specification mini-language – Python documentation
In this article we have padded and aligned strings in Python. See also Python f-string, Python strip string, Python int to string, and Python string case.
Author
List all Python tutorials.