Borislav Hadzhiev
Last updated: Jun 20, 2022
Check out my new book
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.
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:
Name | Description |
---|---|
width | The total length of the padded string |
fillchar | The fill character to pad the string with |
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.
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.
print(repr(' ' * 3)) # 👉️ ' ' print('b' * 3) # 👉️ 'bbb'
You can also use the format string syntax to add spaces to the beginning of a string.
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.
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
.
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}
.