Add a space between two strings in Python

avatar

Borislav Hadzhiev

Last updated: Jun 21, 2022

banner

Photo from Unsplash

Add a space between two strings in Python #

Use a formatted string literal to add a space between two strings in Python, e.g. f'{str_1} {str_2}'. Formatted string literals allow us to include expressions inside of a string by prefixing the string with f.

main.py
str_1 = 'hello' str_2 = 'world' result_1 = f'{str_1} {str_2}' print(result_1) # 👉️ 'hello world'

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 one or more spaces between the strings.

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

main.py
str_1 = 'hello' str_2 = 'world' result = '{} {}'.format(str_1, str_2) print(result) # 👉️ 'hello world'

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

You can also use the str.join() method to achieve the same result.

main.py
str_1 = 'hello' str_2 = 'world' result = ' '.join([str_1, str_2]) print(result) # 👉️ 'hello world'

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.

The string the method is called on is used as the separator between elements.

You can also use the addition (+) operator to add a space between two strings.

main.py
str_1 = 'hello' str_2 = 'world' result = str_1 + ' ' + str_2 print(result) # 👉️ 'hello world'

We can concatenate strings using the addition (+) operator.

If you need to add multiple spaces between the strings, you can multiply a string containing a space by the specified number of spaces to make your code more readable.

main.py
str_1 = 'hello' str_2 = 'world' result = str_1 + ' ' * 3 + str_2 print(repr(result)) # 👉️ 'hello world'
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.