Add a certain number of spaces to a String in Python

avatar

Borislav Hadzhiev

Last updated: Jun 20, 2022

banner

Photo from Unsplash

Add a certain number of spaces to a String in Python #

Use the multiplication operator to add a certain number of spaces to a string, e.g. result_1 = my_str + ' ' * 3. When a character is multiplied, it gets repeated the specified number of times.

main.py
my_str = 'abc' # ✅ add spaces to end of string result_1 = my_str + ' ' * 3 print(repr(result_1)) # 👉️ 'abc ' # ✅ add spaces to beginning of string result_2 = ' ' * 3 + my_str print(repr(result_2)) # 👉️ ' abc' # # ✅ pad end of string with spaces result_3 = my_str.ljust(6, ' ') print(repr(result_3)) # 👉️ 'abc ' # ✅ pad beginning of string with spaces result_4 = my_str.rjust(6, ' ') print(repr(result_4)) # 👉️ ' abc' # ✅ add spaces between the characters of a string result_5 = ' '.join(my_str) print(repr(result_5)) # 👉️ 'a b c' # ✅ add spaces in the middle of a string my_str_2 = 'helloworld' idx = my_str_2.index('w') result_6 = my_str_2[0:idx] + ' ' * 3 + my_str_2[idx:] print(repr(result_6)) # 👉️ 'hello world'

The first two examples use the multiplication operator to add spaces to a string.

main.py
my_str = 'abc' result_1 = my_str + ' ' * 3 print(repr(result_1)) # 👉️ 'abc ' result_2 = ' ' * 3 + my_str print(repr(result_2)) # 👉️ ' abc'

When a character is multiplied, it gets repeated the specified number of times.

main.py
print(repr(' ' * 3)) # 👉️ ' ' print('a' * 3) # 👉️ 'aaa'

You can also use the str.ljust and str.rjust methods to pad the string with spaces to a specified width.

main.py
my_str = 'abc' result_3 = my_str.ljust(6, ' ') print(repr(result_3)) # 👉️ 'abc ' result_4 = my_str.rjust(6, ' ') print(repr(result_4)) # 👉️ ' abc'

The str.ljust (left justify) and str.rjust (right justify) methods take the total width of the string and a fill character as arguments and pad the string to the specified width with the provided fill character.

If you need to add spaces between the characters of a string, use the join() method.

main.py
my_str = 'abc' result_5 = ' '.join(my_str) print(repr(result_5)) # 👉️ 'a b c'

The str.join method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.

If you need to add spaces in the middle of a string, use string slicing.

main.py
my_str_2 = 'helloworld' idx = my_str_2.index('w') result_6 = my_str_2[0:idx] + ' ' * 3 + my_str_2[idx:] print(repr(result_6)) # 👉️ 'hello world'

The syntax for string slicing is my_str[start:stop:step].

The start value is inclusive, and the stop value is exclusive (up to, but not including).

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.