How To Add Space In A String Python

In Python, strings are a sequence of characters, and sometimes we need to add spaces to these strings to improve readability, formatting, or other requirements. This tutorial will teach you how to add spaces in a string using Python.

Step 1: Using String Concatenation

The most basic way to add spaces to a string is using string concatenation, which is done using the + operator. You can simply concatenate a space character (' ') to your string.

In this example, the string_with_space variable will contain the string “Hello World”.

Step 2: Using the .join() Method

Another approach to adding spaces to a string is using the .join() method. This method concatenates all the elements in the input iterable (such as a list or tuple) into a single string, using the specified delimiter. Here’s an example:

In this example, the string_with_space variable will again contain the string “Hello World”.

Step 3: Using the * Operator and String Slicing

You can also add multiple spaces to a string using the * operator, which repeats a given string a specified number of times.

Here’s an example where we add 4 spaces between the words “Hello” and “World”:

In this example, the string_with_spaces variable will contain the string “Hello    World”.

Full Code

Below is the full code for all three methods outlined above:

Output

Hello World
Hello World
Hello    World

Conclusion

In this tutorial, you’ve learned three different ways to add spaces to a string in Python: using string concatenation, the .join() method, and the * operator combined with string slicing. Now, you can easily add spaces to your strings in Python as required for your specific use cases.