Add spaces to the beginning of a String in Python

avatar

Borislav Hadzhiev

Last updated: Jun 20, 2022

banner

Check out my new book

Add spaces to the beginning of a String in Python #

Use the str.rjust() method to add spaces to the beginning of a string, e.g. result = my_str.rjust(6, ' '). The rjust method takes the total width of the string and a fill character and pads the beginning of the string to the specified width with the provided fill character.

main.py
my_str = 'abc' result_1 = my_str.rjust(6, ' ') print(repr(result_1)) # 👉️ ' abc' result_2 = " " * 3 + my_str print(repr(result_2)) # 👉️ ' abc' result_3 = f'{my_str: >6}' print(repr(result_3)) # 👉️ ' abc'

The first example in the code snippet uses the str.rjust (right justify) method.

The str.rjust method takes the following 2 arguments:

NameDescription
widthThe total length of the padded string
fillcharThe fill character to pad the string with
The rjust method pads the beginning of the string to the specified width with the provided fill character.

An alternative solution is to use the multiplication operator to add a specific number of spaces to the beginning of the string.

main.py
my_str = '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('b' * 3) # 👉️ 'bbb'

You can also use the format string syntax to add spaces to the beginning of a string.

main.py
my_str = 'abc' result_3 = f'{my_str: >6}' print(repr(result_3)) # 👉️ ' abc'

This is a bit harder to read, but we basically fill the string to a length of 6 characters aligning it to the right.

If you have the total length of the string stored in a variable, use curly braces.

main.py
width = 6 result_3 = f'{my_str: >{width}}' print(repr(result_3)) # 👉️ ' abc'

Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.

main.py
my_str = 'is subscribed:' my_bool = True result = f'{my_str} {my_bool}' print(result) # 👉️ is subscribed: True

Make sure to wrap expressions in curly braces - {expression}.

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.