How to print a Tab in Python

avatar
Borislav Hadzhiev

Last updated: Apr 10, 2024
8 min

banner

# Table of Contents

  1. How to print a Tab in Python
  2. Print a tab when formatting a string
  3. Print a tab using the addition (+) operator
  4. Join a list of strings with a tab separator
  5. Get a left-justified string of length N
  6. Insert a tab at a specific index into an existing string
  7. Writing tab-separated values to a File in Python
  8. How to print spaces in Python

# How to print a Tab in Python

Use the \t character to print a tab, e.g. print('bobby\thadz'). The \t character inside the string is the escape sequence for the tab character.

main.py
string = 'bobby\thadz' print(string) # ๐Ÿ‘‰๏ธ bobby hadz print(repr('\t')) # ๐Ÿ‘‰๏ธ '\t' tab = '\t' string = f'bobby{tab}hadz' print(string) # ๐Ÿ‘‰๏ธ bobby hadz first = 'bobby' last = 'hadz' print(first + '\t' + last) # ๐Ÿ‘‰๏ธ bobby hadz print('a', 'b', 'c', sep='\t') # ๐Ÿ‘‰๏ธ 'a b c'

print tab in python

The code for this article is available on GitHub

If you just need to print a tab, use the \t character in a string.

main.py
string = 'bobby\thadz' print(string) # ๐Ÿ‘‰๏ธ bobby hadz

The \t character inserts a tab in the string.

If you need to print the literal tab character, pass the string to the repr() function.

main.py
print(repr('\t')) # ๐Ÿ‘‰๏ธ '\t'

# Print a tab when formatting a string

If you need to print a tab when formatting a string, use a formatted string literal.

main.py
tab = '\t' string = f'bobby{tab}hadz' print(string) # ๐Ÿ‘‰๏ธ bobby hadz

print tab when formatting string

The code for this article is available on GitHub
Notice that we stored the \t character in a variable. This is because f-strings cannot contain backslash characters in expressions.

Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.

main.py
tab = '\t' first = 'bobby' last = 'hadz' string = f'{first}{tab}{last}' print(string) # ๐Ÿ‘‰๏ธ bobby hadz

Make sure to wrap expressions in curly braces - {expression}.

You can use backslashes between the expressions of a formatted string literal.

main.py
first = 'bobby' last = 'hadz' salary = 50 string = f"{first}\t{last}\t{salary}" print(string) # ๐Ÿ‘‰๏ธ bobby hadz 50

# Print a tab when formatting a string using str.format()

Alternatively, you can use the str.format() method.

main.py
first = 'bobby' last = 'hadz' string = '{}\t{}'.format(first, last) print(string) # ๐Ÿ‘‰๏ธ bobby hadz

print tab when formatting string with str format

The code for this article is available on GitHub

The str.format() method performs string formatting operations.

The string the method is called on can contain replacement fields specified using curly braces {}.

# Print a tab using the addition (+) operator

Alternatively, you can use the addition (+) operator.

main.py
first = 'bobby' last = 'hadz' age = 30 # ๐Ÿ‘‡๏ธ bobby hadz 30 print(first + '\t' + last + '\t' + str(age))

print tab using addition operator

The addition (+) operator can be used to concatenate strings.

However, you have to make sure that the values on the left and right-hand sides of the operator are of type string.

If you have values of a different type, use the str() class to convert them to strings.

Use the sep keyword argument of the print() function if you need to separate multiple values with a tab when printing them.

main.py
print('a', 'b', 'c', sep='\t') # ๐Ÿ‘‰๏ธ 'a b c'

The sep argument is the separator between the arguments we pass to print().

main.py
print('bobby', 'hadz', sep='') # ๐Ÿ‘‰๏ธ bobbyhadz print('bobby', 'hadz') # ๐Ÿ‘‰๏ธ bobby hadz

By default, the sep argument is set to a space.

# Join a list of strings with a tab separator

You can also use the str.join() method to join multiple strings with a tab separator.

main.py
a_list = ['bobby', 'hadz', 'com'] result = '\t'.join(a_list) print(result) # ๐Ÿ‘‰๏ธ bobby hadz com

join list of strings with tab separator

The code for this article is available on GitHub

The str.join() method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.

Note that the method raises a TypeError if there are any non-string values in the iterable.

If your iterable contains numbers or other types, convert all of the values to strings before calling join().
main.py
a_list = ['bobby', 1, 'hadz', 2, 'com'] result = '\t'.join(str(item) for item in a_list) print(result) # ๐Ÿ‘‰๏ธ bobby 1 hadz 2 com

The string the method is called on is used as the separator between the elements.

Alternatively, you can access each list item at an index and use the addition (+) operator.

main.py
a_list = ['bobby', 1, 'hadz'] result = a_list[0] + '\t' + str(a_list[1]) + '\t' + a_list[2] print(result) # ๐Ÿ‘‰๏ธ bobby 1 hadz

Notice that we had to use the str() class to convert the integer value to a string to be able to use the addition (+) operator.

Python indexes are zero-based, so the first item in a list has an index of 0, and the last item has an index of -1 or len(my_list) - 1.

# Get a left-justified string of length N

If you need to return a left-justified string of a specific length, use the str.ljust() method.

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

get left aligned string of length n

The code for this article is available on GitHub

The str.ljust() method pads the end of the string to the specified width with the provided fill character.

The str.ljust method takes the following 2 arguments:

NameDescription
widthThe total length of the padded string
fillcharThe fill character to pad the string with

When no fillchar is specified, the string is padded with spaces.

# Insert a tab at a specific index into an existing string

If you need to insert a tab at a specific index into an existing string, use string slicing.

main.py
string = 'bobbyhadz' new_string = string[:5] + '\t' + string[5:] print(new_string) # ๐Ÿ‘‰๏ธ bobby hadz

The syntax for string slicing is my_str[start:stop:step].

The start index is inclusive, whereas the stop index is exclusive (up to, but not including).

Python indexes are zero-based, so the first character in a string has an index of 0, and the last character has an index of -1 or len(my_str) - 1.

The slice string[:5] starts at index 0 and goes up to, but not including index 5.

The slice string[5:] starts at index 5 and goes to the end of the string.

# Writing tab-separated values to a File in Python

To write tab-separated values to a file:

  1. Open the file in writing mode.
  2. Use the \t character to insert a tab in a string.
  3. Use the file.write() method to write the string to the file.
main.py
# โœ… write strings separated by tabs to file with open('example.txt', 'w', encoding='utf-8') as my_file: my_file.write('bobby' + '\t' + 'hadz' + '\n') my_file.write('first\tsecond') # โœ… separate the items of a list by tabs and write the result to a file with open('example.txt', 'w', encoding='utf-8') as my_file: my_list = ['bobby', 'hadz', 'com'] my_file.write('\t'.join(my_list) + '\n')
The code for this article is available on GitHub

We used the with statement to open the file in writing mode.

The with statement automatically takes care of closing the file for us.

If you just need to insert a tab into a string, use the \t character.

main.py
with open('example.txt', 'w', encoding='utf-8') as my_file: my_file.write('bobby' + '\t' + 'hadz' + '\n') my_file.write('first\tsecond')

The contents of the example.txt file look like this.

example.txt
bobby hadz first second

You can read the file to verify it contains tabs.

main.py
with open('example.txt', 'r', encoding='utf-8') as f: lines = f.readlines() print(lines) # ๐Ÿ‘‰๏ธ ['bobby\thadz\n', 'first\tsecond']

You can use the \n character if you need to add a new line after the string.

If you need to separate the items of a list by tabs and write the result to a file, use the str.join() method.
main.py
with open('example.txt', 'w', encoding='utf-8') as my_file: my_list = ['bobby', 'hadz', 'com'] my_file.write('\t'.join(my_list) + '\n')

The str.join method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.

Note that the method raises a TypeError if there are any non-string values in the iterable.

If your iterable contains numbers or other types, convert all of the values to strings before calling join().

main.py
with open('example.txt', 'w', encoding='utf-8') as my_file: my_list = ['bobby', 1, 'hadz', 2, 'com'] my_file.write('\t'.join(str(item) for item in my_list) + '\n')

The string the method is called on is used as the separator between the elements.

We called the str.join() method on a string containing a tab to join the elements in the list with a tab separator.

The contents of the file look like this.

example.txt
bobby 1 hadz 2 com

Alternatively, you can access each list item at an index and use the addition (+) operator.

main.py
with open('example.txt', 'w', encoding='utf-8') as my_file: my_list = ['bobby', 1, 'hadz', 2, 'com'] my_file.write( my_list[0] + '\t' + str(my_list[1]) + '\t' + my_list[2] + '\t' + str(my_list[3]) + '\t' + my_list[4] + '\n' )

The addition (+) operator can be used to concatenate strings.

However, you have to make sure that the values on the left and right-hand sides of the operator are of type string.

If you have values of a different type, use the str() class to convert them to strings.

You can also use a for loop to iterate over the list and add a tab after each item.

main.py
with open('example.txt', 'w', encoding='utf-8') as my_file: my_list = ['bobby', 1, 'hadz', 2, 'com'] for word in my_list: my_file.write(str(word) + '\t') my_file.write('\n')

The for loop iterates over the list and uses the addition (+) operator to add a tab after each item.

The last step is to write a newline (\n) character to the file.

# How to print spaces in Python

Use the multiplication operator to print spaces.

main.py
print(' ') # ๐Ÿ‘‰๏ธ ' ' print(' ' * 5) # ๐Ÿ‘‰๏ธ ' ' print(repr(' ')) # ๐Ÿ‘‰๏ธ ' ' print(repr(' ' * 5)) # ๐Ÿ‘‰๏ธ ' ' space = ' ' print(f'bobby{space * 5}hadz') # ๐Ÿ‘‰๏ธ 'bobby hadz' print('bobby' + ' ' * 5 + 'hadz') # ๐Ÿ‘‰๏ธ 'bobby hadz' print('bobby', 'hadz', 'com') # ๐Ÿ‘‰๏ธ bobby hadz com
The code for this article is available on GitHub

If you just need to print multiple spaces, use the multiplication operator.

When the multiplication operator is used with a string and an integer, it repeats the string the specified number of times.

main.py
print(' ') # ๐Ÿ‘‰๏ธ ' ' print(' ' * 5) # ๐Ÿ‘‰๏ธ ' ' print(repr(' ')) # ๐Ÿ‘‰๏ธ ' ' print(repr(' ' * 5)) # ๐Ÿ‘‰๏ธ ' '

Use the repr() function if you need to print quotes around the string to check its length.

You can also store a space in a variable and multiply the variable by N.

main.py
space = ' ' print(space) # ๐Ÿ‘‰๏ธ ' ' print(space * 5) # ๐Ÿ‘‰๏ธ ' ' print(repr(space)) # ๐Ÿ‘‰๏ธ ' ' print(repr(space * 5)) # ๐Ÿ‘‰๏ธ ' '

# Print an empty line

If you need to print an empty line, call print() without passing it any arguments.

main.py
print('before') print() print('after') # before # after

# Print spaces when formatting a string

If you need to print spaces between variables or when formatting a string, use a formatted string literal.

main.py
space = ' ' print(f'bobby{space * 5}hadz') # ๐Ÿ‘‰๏ธ 'bobby hadz' first = 'bobby' last = 'hadz' print(f'{first}{space * 5}{last}') # ๐Ÿ‘‰๏ธ bobby hadz
The code for this article is available on GitHub

Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.

main.py
var1 = 'bobby' var2 = 'hadz' result = f'{var1}{var2}' print(result) # ๐Ÿ‘‰๏ธ bobbyhadz

Make sure to wrap expressions in curly braces - {expression}.

If you use a string containing a space directly in the formatted string literal, make sure to alternate between single and double quotes.

main.py
print(f'bobby{" " * 5}hadz') # ๐Ÿ‘‰๏ธ 'bobby hadz' first = 'bobby' last = 'hadz' print(f'{first}{" " * 5}{last}') # ๐Ÿ‘‰๏ธ bobby hadz

The f-string is wrapped in single quotes, so we had to use double quotes for the inner string.

If we use single quotes inside the expression as well, we'd terminate the f-string prematurely.

You can also use the addition operator to print spaces.

main.py
first = 'bobby' last = 'hadz' print(first + ' ' * 5 + last) # ๐Ÿ‘‰๏ธ bobby hadz print('bobby' + ' ' * 5 + 'hadz') # ๐Ÿ‘‰๏ธ 'bobby hadz'

The addition operator can be used to concatenate strings.

However, you have to make sure that the values on the left and right-hand sides of the operator are of type string.

If you have values of a different type, use the str() class to convert them to strings.

main.py
print('Number:' + ' ' * 5 + str(100)) # ๐Ÿ‘‰๏ธ Number: 100

If you need to print a single space between multiple values in the call to print(), separate the values with commas.

main.py
print('bobby', 'hadz', 'com') # ๐Ÿ‘‰๏ธ bobby hadz com

The sep argument is the separator between the arguments we pass to print().

main.py
print('bobby', 'hadz', sep='') # ๐Ÿ‘‰๏ธ bobbyhadz print('bobby', 'hadz') # ๐Ÿ‘‰๏ธ bobby hadz

By default, the sep argument is set to a space.

The print() function also takes an end argument.

main.py
print('a', 'b', 'c') # ๐Ÿ‘‰๏ธ 'a b c\n' print('a', 'b', 'c', end='') # ๐Ÿ‘‰๏ธ 'a b c'
The code for this article is available on GitHub

The end argument is printed at the end of the message.

By default, end is set to a newline character (\n).

If you set the end argument to an empty string, no newline character is added at the end of the message.

I've also written an article on how to print a new line after a variable.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev