Add spaces between the characters of a string in Python

avatar

Borislav Hadzhiev

Last updated: Jun 21, 2022

banner

Photo from Unsplash

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 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'

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'

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.

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.