Quick Tip To Add A Space Between Two Strings In Python

Add a space between two strings in Python

This post will show you how to add a space between two strings in Python. This is a task that is often needed when you print text on the screen. Let’s see the way to add it.

Add a space between two strings in Python

Here are four methods we’d like to share with you. Read and decide for yourself which method is best for you.

Using the + operator

We can concatenate two strings and add a space between them using the add (+) operator. For example, if you have two strings: “Hello” and “LearnShareIT“, you can use the following code to combine them into “Hello LearnShareIT“:

str1 = "Hello"
str2 = "LearnShareIT"

# Concatenate and add space between two strings using the + operator
newStr = str1 + " " + str2
print(newStr)

Output:

Hello LearnShareIT

Using the f-string

We mentioned the f-string syntax in the previous posts. You can learn more about it here.

When you want to add a space between two strings in Python, you can use the f-string. The f-string is a string literal that allows you to interpolate variables into the string. For example, if you have two strings, “Hello” and “LearnShareIT“, and you want to put a space between them, you would use the following code:

str1 = "Hello"
str2 = "LearnShareIT"

# Add a space between two strings using f-string
newStr = f"{str1} {str2}"
print(newStr)

Output:

Hello LearnShareIT

Using format() function

Adding a space between two strings in Python is simple with the format() function. Simply pass in the two strings you want to add a space between and use the placeholder “{} {}” to indicate where you want the space to be, as an example below.

str1 = "Hello"
str2 = "LearnShareIT"

# Add a space between two strings using format()
newStr = '{} {}'.format(str1, str2)
print(newStr)

Output:

Hello LearnShareIT

Using join() function

The join() function allows you to combine multiple strings into one by using a delimiter of your choice. You can read more about its syntax here.

To add a space between two strings, simply pass the two strings you want to join together as a list to the join() function. Remember to include a white space before calling the join() function. The join() function will return a new string that includes the space between the two strings.

str1 = "Hello"
str2 = "LearnShareIT"

# Add a space between two strings using join()
newStr = ' '.join([str1, str2])
print(newStr)

Output:

Hello LearnShareIT

Summary

Python is a beautiful language. As you can see, Python can insert a space between two strings in various ways while being extremely concise, which many other languages, such as C, JAVA, and PHP, cannot. We hope you like the article about how to add a space between two strings in Python.

Happy coding!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *