Add spaces to Beginning, End or between chars in Python

avatar
Borislav Hadzhiev

Last updated: Apr 8, 2024
7 min

banner

# Table of Contents

  1. Add spaces to the end of a String in Python
  2. Add spaces to the beginning of a String in Python
  3. Add space between variables in Python
  4. Add spaces between the characters of a string in Python

# Add spaces to the end of a String in Python

Use the str.ljust() method to add spaces to the end of a string, e.g. result = my_str.ljust(6, ' ').

The ljust method takes the total width of the string and a fill character and pads the end of the string to the specified width with the provided fill character.

main.py
my_str = 'abc' result_1 = my_str.ljust(6, ' ') print(repr(result_1)) # ๐Ÿ‘‰๏ธ 'abc ' result_2 = my_str + " " * 3 print(repr(result_2)) # ๐Ÿ‘‰๏ธ 'abc ' result_3 = f'{my_str: <6}' print(repr(result_3)) # ๐Ÿ‘‰๏ธ 'abc '

add spaces to end of string

The code for this article is available on GitHub
If you need to add spaces to the beginning of a string, scroll down to the next subheading.

The first example in the code sample uses the str.ljust (left justify) method.

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 ljust method pads the end of the string to the specified width with the provided fill character.

# Adding spaces to the end of a string with the multiplication operator

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

main.py
my_str = 'abc' result = my_str + " " * 3 print(repr(result)) # ๐Ÿ‘‰๏ธ 'abc '

add number of spaces using multiplication operator

The code for this article is available on GitHub

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

main.py
print(repr(' ' * 3)) # ๐Ÿ‘‰๏ธ ' ' print('a' * 3) # ๐Ÿ‘‰๏ธ 'aaa'

# Adding spaces to the end of a string with a formatted string literal

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

main.py
my_str = 'abc' result = f'{my_str: <6}' print(repr(result)) # ๐Ÿ‘‰๏ธ 'abc '

add spaces to end of string with formatted string literal

The code for this article is available on GitHub

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

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

main.py
my_str = 'abc' width = 6 result_3 = f'{my_str: <{width}}' print(repr(result_3)) # ๐Ÿ‘‰๏ธ 'abc '

using curly braces in formatted string literal

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
The code for this article is available on GitHub

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

# Table of Contents

  1. Add spaces to the beginning of a String in Python
  2. Add space between variables in Python
  3. Add spaces between the characters of a string in Python

# Add spaces to the beginning of a String in Python

Use the str.rjust() method to add spaces to the beginning of a string.

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'

add spaces to beginning of string

The code for this article is available on GitHub

The first example in the code sample 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.

# Add spaces to the beginning of a String using the multiplication operator

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'

# Add spaces to the beginning of a String using an f-string

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'

add spaces to beginning of string using f string

The code for this article is available on GitHub

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}.

# Table of Contents

  1. Add space between variables in Python
  2. Add spaces between the characters of a string in Python

# Add space between variables in Python

You can also use a formatted string literal to add a space between variables.

main.py
var_1 = 'hello' var_2 = 123 result = f'{var_1} {var_2}' print(result) # ๐Ÿ‘‰๏ธ hello 123

add space between variables

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}.

You can use this approach to add space between as many variables as necessary.

A formatted string literal can be used to add a space between two strings or two values of different types.

The values get automatically converted to a string when used in a formatted string literal.

Alternatively, you can use the str.join() method to add space between variables.

# Add space between variables using str.join()

This is a two-step process:

  1. Wrap the variables in a list.
  2. Use the str.join() method to join the list with a space separator.
main.py
var_1 = 'hello' var_2 = 123 result_2 = ' '.join(map(str, [var_1, var_2])) print(result_2) # ๐Ÿ‘‰๏ธ hello 123
The code for this article is available on GitHub

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

Note that the method raises a TypeError if there are any non-string values in the iterable.

If your list of variables contains numbers or other types, convert all of the values to strings before calling join().

The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.

We used the map() function to convert the integer stored in var_2 to a string but this isn't necessary if you are only joining strings.

main.py
var_1 = 'hello' var_2 = 'world' result_2 = ' '.join([var_1, var_2]) print(result_2) # ๐Ÿ‘‰๏ธ hello world

The code sample adds a space between the two strings.

# Add space between variables using str.format()

Alternatively, you can use the str.format() method.

main.py
var_1 = 'hello' var_2 = 123 result = '{} {}'.format(var_1, var_2) print(result) # ๐Ÿ‘‰๏ธ 'hello 123'

The str.format() method performs string formatting operations.

main.py
first = 'James' last = 'Doe' result = "His name is {} {}".format(first, last) print(result) # ๐Ÿ‘‰๏ธ "His name is James Doe"

The string the method is called on can contain replacement fields specified using curly braces {}.

# Add space between variables using the addition (+) operator

You can also use the addition (+) operator to add a space between two variables, but make sure they are of compatible types.

main.py
var_1 = 'hello' var_2 = 123 result = var_1 + ' ' + str(var_2) print(result) # ๐Ÿ‘‰๏ธ 'hello 123'
The code for this article is available on GitHub
Notice that we used the str() class to convert the integer to a string so we can concatenate the variables with a space in between.

When using the addition (+) operator, make sure the values on the left and right-hand sides are strings.

If you need to add multiple spaces between variables, use the multiplication operator to make your code more readable.

main.py
var_1 = 'hello' var_2 = 123 result = var_1 + ' ' * 3 + str(var_2) print(repr(result)) # ๐Ÿ‘‰๏ธ 'hello 123'

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

main.py
print(repr(' ' * 3)) # ๐Ÿ‘‰๏ธ ' ' print(repr('a' * 3)) # ๐Ÿ‘‰๏ธ 'aaa'

Formatted string literals take care of automatically converting the values to strings, so we don't have to explicitly use the str() class in the values are of different types.

# Add spaces between the characters of a string in Python

To add spaces between the characters of a string:

  1. Call the join() method on a string containing a space.
  2. Pass the string as an argument to the join method.
  3. The method will return a string where the characters are separated by a space.
main.py
my_str = 'abcde' result = ' '.join(my_str) print(result) # ๐Ÿ‘‰๏ธ 'a b c d e'
The code for this article is available on GitHub

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

When called with a string argument, the join method adds the provided separator between each of the characters.

main.py
my_str = 'abcde' result = '_'.join(my_str) print(result) # ๐Ÿ‘‰๏ธ 'a_b_c_d_e'

To insert spaces between the characters, call the join method on a string containing a space.

main.py
my_str = 'abcde' result = ' '.join(my_str) print(result) # ๐Ÿ‘‰๏ธ 'a b c d e'

You can also add multiple spaces if you need to separate the characters by more than 1 space.

main.py
my_str = 'abcde' result = ' '.join(my_str) print(result) # ๐Ÿ‘‰๏ธ 'a b c d e'

# Add spaces between the characters of a string using a for loop

An alternative approach is to iterate over the string and add spaces between the characters manually.

main.py
my_str = 'abcde' result = '' for char in my_str: result += char + ' ' * 1 result = result.strip() print(repr(result)) # ๐Ÿ‘‰๏ธ 'a b c d e'
The code for this article is available on GitHub

Note that this approach is much more inefficient than using str.join().

You can multiply a string by a specific number to repeat the string N times.

main.py
print(repr(' ' * 3)) # ๐Ÿ‘‰๏ธ ' ' print(repr('a' * 3)) # ๐Ÿ‘‰๏ธ 'aaa'

If you need to remove the trailing spaces after the last character, use the strip() method.

The str.strip() method returns a copy of the string with the leading and trailing whitespace removed.

The method does not change the original string, it returns a new string. Strings are immutable in Python.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev