Adding a space between two strings is a common procedure while working with Python, a popular programming language due to its readability and ease of use.
Learning how to manipulate strings is a crucial aspect of any programming job, and Python makes it easy with its powerful string methods. In this tutorial, we’ll walk you through how to add space between two strings in Python.
Step One: Declare Strings
To add a space, first, we need two strings. A string in Python is a sequence of characters. It can be declared with either single quotes (‘ ‘) or double quotes (” “). Let’s declare two strings:
1 2 |
string1 = 'Hello' string2 = 'World' |
Step Two: Using the ‘+’ Operator
Now to add a space between these two strings, we’ll use the ‘+’ operator. Python supports string concatenation using the ‘+’ operator. Python automatically converts numbers to strings when you use such an operator between strings and numbers. Here’s how you do it:
1 |
result = string1 + ' ' + string2 |
As we can see, we’ve added an extra ‘ ‘ between string1 and string2. The ‘ ‘ is actually a string containing a space character. So, we are concatenating three strings here: string1, a space, and string2.
Step Three: Print the Result
Finally, let’s print out the result to check if a space has been added:
1 |
print(result) |
Full Code
1 2 3 4 |
string1 = 'Hello' string2 = 'World' result = string1 + ' ' + string2 print(result) |
Output:
'Hello World'
Conclusion:
And that’s it! You’ve successfully added a space between two strings in Python. This method can be applied in many scenarios while you’re manipulating strings in Python. Practice more with different strings and operators to familiarize yourself with Python string manipulation.