In everyday programming work, there are times when you will want to print data to the screen in tab form. The article will show you the simplest and easiest ways to do this. Let’s find out together.
Ways to print a tab in Python
There are many ways to print a tab in Python in various data scenarios. For example, using \t
or inserting the TAB sign directly into the string, I’ll start with the simplest and most commonly used method.
Use \t
in string
The Python documentation shows many string literals that can be used in strings. The “\” is a special character which is used to create a space. Where \t
is utilized to build a tab in the horizontal direction. We will insert \t
into the string to be tabulated. This is the simplest way to print a tab character.
Example:
# Use \t in strings name = "J\to\th\tn" print(name)
Output:
J o h n
If the data is a List, we can also use it like this:
Example:
fruits = ["apple", "banana", "cherry"] # Use \t in List print(fruits[0] + "\t" + fruits[1] + "\t" + fruits[2])
Output:
apple banana cherry
Using \t in f-string expression
To use \t
in an f-string expression, you assign \t
to a variable.
Example:
fruits = ["apple", "banana", "cherry"] # Assign \t to a variable and use it in f-string expression tab = "\t" print(f"{fruits[0] + tab + fruits[1] + tab + fruits[2]}")
Output:
apple banana cherry
Use \N{TAB}
If you don’t want to use the escape sequence, you can insert the TAB character directly into the string.
Example:
# Insert the TAB character directly into the string couple = "John\N{TAB}and\N{TAB}Mary" print(couple)
Output:
John and Mary
Use “sep” variable
You can convert strings to characters and use tabs to separate them.
Example:
name = "John" # Assign \t to "sep" variable print(*name, sep="\t")
Output:
J o h n
Use “str.join”
You can use the join()
method of the string object to split the string into characters.
Example:
name = "Mary" # Use join() method print('\t'.join(name))
Output:
M a r y
Use “chr(9)”
If you don’t want to use escape sequences, you can use the “chr(9)
” character.
Example:
# Insert the character "chr(9)" into the string couple = "Mary" + chr(9) + "and" + chr(9) + "John" print(couple)
Output:
Mary and John
Summary
Through the article, we have learned together about the ways to print a tab in Python. The easiest way is to use \t
escape sequences. Hope the article will help you in your work. Good luck.
Carolyn Hise has three years of software development expertise. Strong familiarity with the following languages is required: Python, Typescript/Nodejs, .Net, Java, C++, and a strong foundation in Object-oriented programming (OOP).