174

Let's say I have a file. How do I write "hello" TAB "alex"?

codeforester
  • 39,467
  • 16
  • 112
  • 140
TIMEX
  • 259,804
  • 351
  • 777
  • 1,080

7 Answers7

201

This is the code:

f = open(filename, 'w')
f.write("hello\talex")

The \t inside the string is the escape sequence for the horizontal tabulation.

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
Simone
  • 11,655
  • 1
  • 30
  • 43
  • 11
    Using `print "a\tb"` gives me `a (8 spaces)b` in the `cmd` on `Windows`. Why is it printing 8 spaces instead of the tab character. – Iulian Onofrei Mar 15 '15 at 16:47
  • What else were you expecting? – Simone Mar 16 '15 at 08:20
  • 12
    To display `a (tab character)b` – Iulian Onofrei Mar 16 '15 at 09:13
  • @IulianOnofrei A tab character is a non-printing character, also known as whitespace. You don't see anything when press the Tab key. It just moves the text over by a default number of spaces. Maybe you can draw in characters what you want to appear. Is it --> ? – Rick Henderson May 20 '16 at 15:29
  • 5
    @RickHenderson That's not true, a tab character is not just a number of spaces. Maybe your Editor is configured to insert spaces on pressing tab. " " is a tab " " is a space. You may not see the difference here, but open up Word/Libre and you will see the difference. – Patrik Apr 18 '18 at 10:38
  • @Sativa I'm well aware of that thanks. A more correct statement would be the tab moves the text over by a set distance. – Rick Henderson Apr 24 '18 at 14:43
  • @RickHenderson that isn't true either. A tab should put the next character at the next tab stop, whose distance is variable based on the tab spacing and how long the preceding string is. – Foo Bar Jul 09 '20 at 18:00
  • 1
    @IulianOnofrei that might be an implementation issue in cmd itself. Monospace consoles may handle text display differently than a text editor would, and auto-convert tabs into spaces on screen. – Foo Bar Jul 09 '20 at 18:14
42

The Python reference manual includes several string literals that can be used in a string. These special sequences of characters are replaced by the intended meaning of the escape sequence.

Here is a table of some of the more useful escape sequences and a description of the output from them.

Escape Sequence       Meaning
\t                    Tab
\\                    Inserts a back slash (\)
\'                    Inserts a single quote (')
\"                    Inserts a double quote (")
\n                    Inserts a ASCII Linefeed (a new line)

Basic Example

If i wanted to print some data points separated by a tab space I could print this string.

DataString = "0\t12\t24"
print (DataString)

Returns

0    12    24

Example for Lists

Here is another example where we are printing the items of list and we want to sperate the items by a TAB.

DataPoints = [0,12,24]
print (str(DataPoints[0]) + "\t" + str(DataPoints[1]) + "\t" + str(DataPoints[2]))

Returns

0    12    24

Raw Strings

Note that raw strings (a string which include a prefix "r"), string literals will be ignored. This allows these special sequences of characters to be included in strings without being changed.

DataString = r"0\t12\t24"
print (DataString)

Returns

0\t12\t24

Which maybe an undesired output

String Lengths

It should also be noted that string literals are only one character in length.

DataString = "0\t12\t24"
print (len(DataString))

Returns

7

The raw string has a length of 9.

CodeCupboard
  • 1,507
  • 3
  • 17
  • 26
  • I need to have a space between my elements that is around half of `\t`. How can I do this? – seralouk Apr 02 '20 at 12:36
  • The Example for Lists is an eyesore. `"\t".join(map(str, DataPoints))` or `print("{}\t{}\t{}".format(*DataPoints))` are significantly DRYer. – Joooeey Apr 18 '23 at 18:56
28

You can use \t in a string literal:

"hello\talex"

Knio
  • 6,638
  • 3
  • 29
  • 29
15

It's usually \t in command-line interfaces, which will convert the char \t into the whitespace tab character.

For example, hello\talex -> hello--->alex.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Darbio
  • 11,286
  • 12
  • 60
  • 100
15

As it wasn't mentioned in any answers, just in case you want to align and space your text, you can use the string format features. (above python 2.5) Of course \t is actually a TAB token whereas the described method generates spaces.

Example:

print "{0:30} {1}".format("hi", "yes")
> hi                             yes

Another Example, left aligned:

print("{0:<10} {1:<10} {2:<10}".format(1.0, 2.2, 4.4))
>1.0        2.2        4.4 
user1767754
  • 23,311
  • 18
  • 141
  • 164
4

Here are some more exotic Python 3 ways to get "hello" TAB "alex" (tested with Python 3.6.10):

"hello\N{TAB}alex"

"hello\N{tab}alex"

"hello\N{TaB}alex"

"hello\N{HT}alex"

"hello\N{CHARACTER TABULATION}alex"

"hello\N{HORIZONTAL TABULATION}alex"

"hello\x09alex"

"hello\u0009alex"

"hello\U00000009alex"

Actually, instead of using an escape sequence, it is possible to insert tab symbol directly into the string literal. Here is the code with a tabulation character to copy and try:

"hello alex"

If the tab in the string above won't be lost anywhere during copying the string then "print(repr(< string from above >)" should print 'hello\talex'.

See respective Python documentation for reference.

Pavel Shishpor
  • 742
  • 6
  • 14
2

Assume I have a variable named file that contains a file. Then I could use file.write("hello\talex").

  1. file.write("hello means I'm starting to write to this file.
  2. \t means a tab
  3. alex") is the rest I'm writing