Concatenate strings with space in Python

This article gives you an idea to learn about the concatenation of strings with space in Python. A String is a collection of Unicode characters represented by a byte array in Python. Strings are concatenated when one string is added to another. Concatenation of strings can be done in many ways to combine the two strings. Some ways to add string space in Python are given below.

Method 1: Using the ‘+’ operator

String concatenation can be easily done with the help of using the + operator. It can be used to add multiple strings in a chain. Since strings cannot be mutated, they are assigned to new variables each time they are concatenated. Defining and concatenating the strings is the first step, followed by using a string separator (” “) after the first string. For a better understanding look at the code given below.

# Define the strings
var1 = "Hello"
var2 = "Codespeedy"
 
# use '+' Operator to combine with the separator space between them
var3 = (var1 + " " +var2)
# Print the concatenation with space between them
print(var3)

Output:

HelloCodespeedy
Hello Codespeedy

Also read: How to concatenate two strings in Python

Method 2: Using .join() method

This method will also help you to learn how to concatenate the strings with space in Python in a different manner. In join() method, the elements of the sequence are joined together with a string separator between them to produce another string. Firstly define the strings that are to be concatenated and then use the join() method to combine the string and at last use the string separator space to the resultant variable which is the combination of the defined strings and print the output. The code for this particular method is given below for a better understanding of the concept.

#define the strings
var1 = "Hello"
var2 = "Codespeedy"
 
#use the join() method to add two strings
print("".join([var1, var2]))
 

# Use the string separator Space(" ")
var3 = " ".join([var1, var2])
# Print the result 
print(var3)

Output:

HelloCodespeedy
Hello Codespeedy

Leave a Reply

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