Add X number of spaces to a string in Python

avatar

Borislav Hadzhiev

Last updated: Aug 29, 2022

banner

Photo from Unsplash

Add X number of spaces to a string in Python #

Use the multiplication operator to add X number of spaces to a string, e.g. result = my_str + ' ' * 2. The multiplication operator will repeat the space the specified number of times and the addition (+) operator will concatenate the two strings.

main.py
my_str = 'abc' # ✅ using addition operator with multiplication result = ' ' * 2 + my_str print(repr(result)) # 👉️ ' abc' result = my_str + ' ' * 2 print(repr(result)) # 👉️ 'abc ' # ---------------------------------- num_of_spaces = 2 # ✅ add trailing spaces to string result = my_str.ljust(len(my_str) + num_of_spaces, ' ') print(repr(result)) # 👉️ 'abc ' # ✅ add leading spaces to string result = my_str.rjust(len(my_str) + num_of_spaces, ' ') print(repr(result)) # 👉️ ' abc'

The first example uses the multiplication operator to add spaces to a string.

The multiplication operator can be used to repeat a string a specified number of times.

main.py
my_str = 'abc' result = ' ' * 2 + my_str print(repr(result)) # 👉️ ' abc' result = my_str + ' ' * 2 print(repr(result)) # 👉️ 'abc '

We simply repeat a space N times and use the addition operator to concatenate the two strings.

You can use the multiplication operator to repeat any string N times.

main.py
print(repr(' ' * 2)) # 👉️ ' ' print(repr(' ' * 3)) # 👉️ ' ' print('-' * 2) # 👉️ '--' print('-' * 3) # 👉️ '---'

Alternatively, you can use the str.ljust() or str.rjust() methods.

main.py
my_str = 'abc' num_of_spaces = 2 # ✅ add trailing spaces to string result = my_str.ljust(len(my_str) + num_of_spaces, ' ') print(repr(result)) # 👉️ 'abc ' # ✅ add leading spaces to string result = my_str.rjust(len(my_str) + num_of_spaces, ' ') print(repr(result)) # 👉️ ' abc'

The str.ljust method pads the end of the string to the specified width with the provided fill character.

The str.ljust method takes the following 2 arguments:

NameDescription
widthThe total length of the padded string
fillcharThe fill character to pad the string with

The str.rjust method pads the beginning of the string to the specified width with the provided fill character.

We added the number of spaces to be added to the string to its length because the ljust() and rjust() methods take the total length of the padded string.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.