Python: Comma in Print as "\T"

the , in print added a white space

>>> print "a","b"
a b

If I need a \t, I put

>>> print "a","\t","b"
a       b

How I can change the output of , to a \t?

4 Answers

You can import the print() function from __future__ and use sep='\t', print() function was introduced in python 3, and it replaced the print statement used in python 2.x:

In [1]: from __future__ import print_function

In [2]: print('a','b',sep='\t')
a   b

help on print():

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep:  string inserted between values, default a space.
end:  string appended after the last value, default a newline.

Use str.join() instead:

print '\t'.join(('a', 'b'))

The python print statement will convert any element in the expression to string and join them using a space; if you want to use a different delimiter you'll have to do the joining manually.

Alternatively, use the print() function, which has been introduced to ease transition to Python 3:

from __future__ import print_function
print('a','b',sep='\t')

The print() function accepts a sep parameter to alter what string is used to delimit the values. In python 3, only the print() function remains and the old print statement from python 2 has been removed.

The easiest way

print("%s\t%s",%(a,b))
0

like this print "Hello", "workd!",

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest