Last updated: Apr 10, 2024
Reading timeยท8 min
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.
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'
If you just need to print a tab, use the \t
character in a string.
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.
print(repr('\t')) # ๐๏ธ '\t'
If you need to print a tab when formatting a string, use a formatted string literal.
tab = '\t' string = f'bobby{tab}hadz' print(string) # ๐๏ธ bobby hadz
\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
.
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.
first = 'bobby' last = 'hadz' salary = 50 string = f"{first}\t{last}\t{salary}" print(string) # ๐๏ธ bobby hadz 50
str.format()
Alternatively, you can use the str.format()
method.
first = 'bobby' last = 'hadz' string = '{}\t{}'.format(first, last) print(string) # ๐๏ธ bobby hadz
The str.format() method performs string formatting operations.
The string the method is called on can contain replacement fields specified
using curly braces {}
.
Alternatively, you can use the addition (+) operator.
first = 'bobby' last = 'hadz' age = 30 # ๐๏ธ bobby hadz 30 print(first + '\t' + last + '\t' + str(age))
The addition (+) operator can be used to concatenate strings.
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.
print('a', 'b', 'c', sep='\t') # ๐๏ธ 'a b c'
The sep
argument is the separator between the arguments we pass to print()
.
print('bobby', 'hadz', sep='') # ๐๏ธ bobbyhadz print('bobby', 'hadz') # ๐๏ธ bobby hadz
By default, the sep
argument is set to a space.
You can also use the str.join()
method to join multiple strings with a tab
separator.
a_list = ['bobby', 'hadz', 'com'] result = '\t'.join(a_list) print(result) # ๐๏ธ bobby hadz com
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.
join()
.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.
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
.
If you need to return a left-justified string of a specific length, use the
str.ljust()
method.
my_list = ['ab', 'abcd', 'abcdefg'] for item in my_list: print(f'{item.ljust(10)} another') # ab another # abcd another # abcdefg another
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:
Name | Description |
---|---|
width | The total length of the padded string |
fillchar | The fill character to pad the string with |
When no fillchar
is specified, the string is
padded with spaces.
If you need to insert a tab at a specific index into an existing string, use string slicing.
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]
.
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.
To write tab-separated values to a file:
\t
character to insert a tab in a string.file.write()
method to write the string to the file.# โ 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')
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.
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.
bobby hadz first second
You can read the file to verify it contains tabs.
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.
str.join()
method.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()
.
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.
bobby 1 hadz 2 com
Alternatively, you can access each list item at an index and use the addition (+) operator.
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.
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.
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.
Use the multiplication operator to print spaces.
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
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.
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.
space = ' ' print(space) # ๐๏ธ ' ' print(space * 5) # ๐๏ธ ' ' print(repr(space)) # ๐๏ธ ' ' print(repr(space * 5)) # ๐๏ธ ' '
If you need to print an empty line, call print()
without passing it any
arguments.
print('before') print() print('after') # before # after
If you need to print spaces between variables or when formatting a string, use a formatted string literal.
space = ' ' print(f'bobby{space * 5}hadz') # ๐๏ธ 'bobby hadz' first = 'bobby' last = 'hadz' print(f'{first}{space * 5}{last}') # ๐๏ธ bobby hadz
Formatted string literals (f-strings) let us include expressions inside of a
string by prefixing the string with f
.
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.
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.
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.
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.
print('bobby', 'hadz', 'com') # ๐๏ธ bobby hadz com
The sep
argument is the separator between the arguments we pass to print()
.
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.
print('a', 'b', 'c') # ๐๏ธ 'a b c\n' print('a', 'b', 'c', end='') # ๐๏ธ 'a b c'
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.
You can learn more about the related topics by checking out the following tutorials: