How to write a tab in Python?

Say I have a file. How to write "hello" TAB "alex"?

+95
python tabs
Dec 20 '10 at
source share
5 answers

This is the code:

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

\t inside a line is an escape sequence for horizontal tabs.

+122
Dec 20 '10 at 10:07
source share

You can use \ t in a string literal:

"hello\talex"

+23
Dec 20 '10 at 10:05
source share

The Python Reference Guide includes several string literals that you can use in a string. These special character sequences are replaced by the intended escape sequence value.

Here is a table of some of the most useful escape sequences and a description of their output.

 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 space, I could print this line.

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

Returns

 0 12 24 

List example

Here is another example where we print list items and we want to separate items using TAB.

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

Returns

 0 12 24 

Raw lines

Note that raw strings (a string containing the prefix "r"), string literals will be ignored. This allows you to include these special character sequences in strings without modification.

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

Returns

 0\t12\t24 

What could be an undesirable conclusion

Line length

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

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

Returns

 7 

The raw string has a length of 9.

+17
Apr 13 '17 at 11:21 on
source share

This is usually \t on command line interfaces that convert char \t to a tab character as spaces.

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

+14
Dec 20 '10 at
source share

As it was not mentioned in any answers, just in case you want to align and place the text, you can use the functions of the string format. (above python 2.5) Of course, \t is actually a TAB token, while 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 
+6
Nov 18 '17 at 7:02
source share



All Articles