Skip to content

How to print Tab in Python

Learn how to insert, manipulate, and format tabs in Python for aligned output, string formatting, and working with tab-separated files (TSV).

In Python, effectively managing whitespace, i.e., tabs and spaces, is crucial for formatting output, creating readable data files, and manipulating strings.

This comprehensive guide will explore various techniques for working with tabs and spaces, equipping you with the knowledge to handle them confidently in your Python projects.

Printing Tabs in Python

Tabs are typically used to create aligned columns in text. In Python, the \t escape sequence represents a tab character.

1. Using the \t escape sequence

The simplest way to insert a tab is by using \t within a string literal.

string = 'tutorial\treference'
print(string) # Output: tutorial    reference

2. Printing Literal Tab Characters

To represent the actual tab character itself (not its effect), use the repr() function.

print(repr('\t')) # Output: '\t'

3. Tabs in Formatted String Literals (f-strings)

f-strings offer a flexible way to embed tabs. Use a variable to hold the tab character because backslashes can't be used in the expression part of f-strings

tab = '\t'
string = f'tutorial{tab}reference'
print(string) # Output: tutorial    reference

You can also directly use backslash inside the f-string as a string, without storing it into a variable:

first = 'tom'
last = 'nolan'
salary = 500

string = f"{first}\t{last}\t{salary}"
print(string) # Output: tom    nolan    500

4. Tabs with str.format()

The str.format() method provides an alternative approach to formatting strings with tabs.

first = 'tom'
last = 'nolan'
string = '{}\t{}'.format(first, last)
print(string)  # Output: tom    nolan

Using Tabs with Operators and Functions

1. Concatenation with the + operator

You can use the + operator to concatenate strings including tabs:

first = 'tom'
last = 'nolan'
age = 500

print(first + '\t' + last + '\t' + str(age)) # Output: tom    nolan    500

2. Using sep argument in print()

The print() function's sep argument allows you to specify a separator between printed items.

print('a', 'b', 'c', sep='\t') # Output: a    b    c

3. Joining lists of strings with tab separators using str.join()

The str.join() method is perfect for joining a list of strings with a tab separator.

a_list = ['tutorial', 'reference', 'com']
result = '\t'.join(a_list)
print(result) # Output: tutorial    reference    com

If your list contains non-string values, convert them to strings first:

a_list = ['tutorial', 1, 'reference', 2, 'com']
result = '\t'.join(str(item) for item in a_list)
print(result) # Output: tutorial    1   reference    2   com

String Manipulation with Tabs

1. Left-justifying strings with str.ljust()

Use str.ljust() to create left-aligned strings with a fixed width, useful when working with columns.

my_list = ['ab', 'abcd', 'abcdefg']
for item in my_list:
    print(f'{item.ljust(10)}another')

2. Inserting tabs at specific indices using string slicing

String slicing helps insert a tab at a specific position within a string.

string = 'tutorialreference'
new_string = string[:8] + '\t' + string[8:]
print(new_string) # Output: tutorial    reference

Working with Tab-Separated Files (TSV)

1. Writing TSV files

Writing tab-separated values to a file in Python:

with open('example.tsv', 'w', encoding='utf-8') as my_file:
    my_file.write('tutorial\t reference\n')
    my_file.write('first\tsecond\n')

with open('example.tsv', 'w', encoding='utf-8') as my_file:
    my_list = ['tutorial', 'reference', 'com']
    my_file.write('\t'.join(my_list) + '\n')

2. Reading TSV files

To read tab-separated values from a file: open the file in read mode ('r'), use readlines() to read all lines into a list, and then use the split('\t') method on each line to split it into a list of values based on the tab delimiter.

with open('example.tsv', 'r', encoding='utf-8') as f: 
    lines = f.readlines() 
    for line in lines: 
        values = line.strip().split('\t') # Remove potential newline and split 
        print(values) 

Printing Spaces in Python

1. Using the space character and the * operator

The multiplication operator repeats a space character:

print(' ')      # Output: ' '
print(' ' * 5)  # Output: '     '

2. Spaces in Formatted String Literals (f-strings)

space = ' '
print(f'tutorial{space * 5}reference') # Output: tutorial     reference

3. Spaces with the + operator

Concatenate spaces with + operator.

print('tutorial' + ' ' * 5 + 'reference') # Output: tutorial     reference

4. Controlling spacing with commas in print()

Using commas to print multiple values in the print() function will, by default, put a space between them.

print('tutorial', 'reference', 'com') # Output: tutorial reference com

5. Using end argument in print()

Control what is printed at the end using end argument:

print('a', 'b', 'c', end='')  # Output: 'a b c'
Navigation