How do you print a tab character in Python?
The easiest way to print a tab character in Python is to use the short-hand abbreviation
'\t'
(don’t forget the quotation marks – it needs to be parked inside a string). To see the tab-spaced character in the REPL output pane, wrap any variable containing a tab character in the built-in
print()
function.
Here’s a simple example:
>>> my_tabbed_string = 'Space\tman'
>>> print(my_tabbed_string)
Space man
What if you’d prefer to see the tab character instead of the actual spacing?
If in the REPL just return the variable containing the tabbed string on a new line, like so:
>>> my_tabbed_string
'Space\tman'
Here’s a demonstration of both outputs:
It Doesn’t Work For Format String!
You can use the shortcut form of the tab character in most places, but you cannot use
any backslash
character in an
f-string
expression (the commands between the curly braces
{}
).
For example, using the following produces a
SyntaxError
:
>>> print(f"{str(1) + '\t' + str(2)}")
File "<input>", line 1
SyntaxError: f-string expression part cannot include a backslash
As the tab character cannot be used inside the curly braces, simply close the curly braces to enable to tab space to occur within the normal bounds of the string.
If you have to use a tab character within the curly braces, there are a couple of workarounds.
As demonstrated in the post where I use tabs to print a list , you can place the tab character into a variable and reference the “tab variable” in the f-string expression, like so:
>>> tab = "\t"
>>> print(f"{str(1) + tab + str(2)}")
1 2
Using
chr()
Built-In Function
An alternative approach to the shorthand method
'\t'
is using the built-in
chr()
function.
The
chr()
function takes one parameter, an integer ranging from 0 to
1,114,111
, with each number in that range representing a Unicode character.
To find out what the integer representation of the tab character is, you can use another built-in function
ord()
that provides the integer representation of a Unicode character. Using it and confirming like so:
>>> ord('\t')
9
>>> chr(9)
'\t'
As you can see
chr(9)
represents the tab character.
Therefore, another way to print the tab character is to use the
chr(9)
function as it produces the same results as seen from the print statement below:
>>> print(f"{str(1) + chr(9) + str(2)}")
1 2
Here’s a demonstration of each approach:
Print Tab Spaces In Python
To print the tab character, use the abbreviated shorthand method of
'\t'
or
chr(9)
if using backslashes in your context will not work.
Be mindful that the tab space is one of the whitespace characters, meaning if a tab is found at the beginning or trailing end of a string, it will be removed if the
.strip()
method is applied, as follows:
>>> my_string = "\t\tSpaced out\t\t"
>>> print(my_string)
Spaced out
>>> my_string.strip()
'Spaced out'
Next, you might want to read another post about the number of spaces in a tab?
A tab size in Python is 4 spaces.