Skip to Content

How To Print A Tab In Python

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'. To see the tab spaced character in the REPL 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
Python Tutorial 1 - Basics
Python Tutorial 1 - Basics

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

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

There are a couple of ways to get around this limitation (besides not using slashes at all!).

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 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() which provides the integer representation of a Unicode character. Using it and confirming like so:

>>> ord('\t')
>>> chr(9)

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 this produces the same results:

>>> print(f"{str(1) + chr(9) + str(2)")
1	2


To print the tab character use the abbreviated shorthand method of '\t' or chr(9) if using backslashes in your context will not work.

Next, you might want to read another post about how many spaces is a tab?