In this tutorial, we’ll learn how to print space in Python. Printing a space might seem trivial, but it is an essential part of many programs, particularly when it comes to formatting output. By the end of this tutorial, you’ll be able to print space in Python in a few different ways and know when each method is best suited for your specific use case.
Step 1: Printing a Space Using print() Function
In Python, the built-in print()
function is used to print strings and other values on the console. By default, it adds a newline character at the end of the printed text. To print a space, we can use the print function with an empty string as its argument, like this:
1 |
print(" ", end="") |
Here, we’re also using the end=""
argument to remove the newline character at the end of the printed space. This will allow us to print additional text or characters on the same line after the space.
Let’s see an example:
1 2 3 |
print("Hello", end="") print(" ", end="") print("World") |
Output:
Hello World
Step 2: Using a formatted string
Another method is using formatted strings to include spaces in the output. The format()
method comes in handy for this use case. With format()
, you can place placeholders in a string and replace them with values.
For example, let’s use the format()
method to insert a space between two strings:
1 2 3 4 |
string1 = "Hello" string2 = "World" result = "{} {}".format(string1, string2) print(result) |
Output:
Hello World
Step 3: Printing a Space Using String Concatenation
You can also print a space in Python by concatenating a space character with the desired text. Here’s an example:
1 |
print("Hello" + " " + "World") |
Output:
Hello World
Step 4: Printing Multiple Spaces
If you want to print multiple spaces, you can use the space character multiplied by the desired amount of spaces. For instance, here’s how to print a string with 5 spaces in between:
1 |
print("Hello" + " " * 5 + "World") |
Output:
Hello World
Conclusion
In this tutorial, we’ve learned how to print space in Python using various methods, such as:
- The built-in
print()
function - Formatted strings using the
format()
method - String concatenation
- Printing multiple spaces using the space character multiplied by a specific number
Choose the method that best fits your specific use case and formatting needs. Happy coding!