In this tutorial, you will learn how to print output with tab space in Python. The tab space is essential when formatting the output for better readability, especially when working with tables and columns.
Step 1: Using Escape Sequences
One of the simplest ways to print output with tab space in Python is by using escape sequences. In this case, you need to use the escape character \t
to represent the tab space in your strings.
First, let’s create a simple example of printing a table using tab spaces to separate columns.
1 2 3 4 5 6 7 |
# Display table header print("Name\tAge\tCity") # Display table data print("John\t25\tNew York") print("Jane\t30\tLos Angeles") print("Jack\t22\tChicago") |
Output:
Name Age City John 25 New York Jane 30 Los Angeles Jack 22 Chicago
Step 2: Using String Formatting
Python provides string formatting techniques using the format()
method. This method allows you to insert tab spaces between the elements.
In the following example, we’ll recreate the previous table using the format()
method.
1 2 3 4 5 6 7 8 |
# Display table header header = "{0}\t{1}\t{2}" print(header.format("Name", "Age", "City")) # Display table data print(header.format("John", 25, "New York")) print(header.format("Jane", 30, "Los Angeles")) print(header.format("Jack", 22, "Chicago")) |
Output:
Name Age City John 25 New York Jane 30 Los Angeles Jack 22 Chicago
Step 3: Using F-strings (Python 3.6+)
F-strings, introduced in Python 3.6, allow you to embed expressions inside string literals. You can print output with tab space using f-strings by incorporating the tab escape character (\t
) in the expression.
Let’s recreate the table again using f-strings:
1 2 3 4 5 6 7 |
# Display table header print(f"{'Name'}\t{'Age'}\t{'City'}") # Display table data print(f"{'John'}\t{25}\t{'New York'}") print(f"{'Jane'}\t{30}\t{'Los Angeles'}") print(f"{'Jack'}\t{22}\t{'Chicago'}") |
Output:
Name Age City John 25 New York Jane 30 Los Angeles Jack 22 Chicago
Full Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
# Escape Sequences print("Name\tAge\tCity") print("John\t25\tNew York") print("Jane\t30\tLos Angeles") print("Jack\t22\tChicago") # String Formatting header = "{0}\t{1}\t{2}" print(header.format("Name", "Age", "City")) print(header.format("John", 25, "New York")) print(header.format("Jane", 30, "Los Angeles")) print(header.format("Jack", 22, "Chicago")) # F-strings print(f"{'Name'}\t{'Age'}\t{'City'}") print(f"{'John'}\t{25}\t{'New York'}") print(f"{'Jane'}\t{30}\t{'Los Angeles'}") print(f"{'Jack'}\t{22}\t{'Chicago'}") |
Conclusion
In this tutorial, you’ve learned various methods to print output with tab space in Python, including using escape sequences, string formatting, and f-strings. These techniques can enhance the readability of your outputs and make it easier to work with tables and columns. Happy coding!