Python: difference between tab input and \ t in triple quotes

When writing a line in triple quotation marks "", what is the difference in literal input \ n or \ t for a new line or tab and just writing it the way you want inside the quotation marks? Example:

sample = """ I'm writing this 
On separate lines
    And tabs
So why can't I write it like this
/t instead of tabbing like this
\n or new lining like this.
Is one way preferred over the other? """

One of the methods?

+4
source share
4 answers

Remember that it is better to be explicit, not implied. Use specific \tand \nleaves no room for speculation.

+3
source

tab , \t . r"""\t""", \t - ( , ). , ( "", '').

+1

. : \t , . 4 .

@IanAuld, Zen of Python,

, .

\t.

+1

, \t , , , ! ( ).

, . , Makefile Python. , make(1) . ?

makefile = """
main.o : main.c defs.h
        cc -c main.c
kbd.o : kbd.c defs.h command.h
        cc -c kbd.c
command.o : command.c defs.h command.h
        cc -c command.c
"""

makefile = """
main.o : main.c defs.h
\tcc -c main.c
kbd.o : kbd.c defs.h command.h
\tcc -c kbd.c
command.o : command.c defs.h command.h
\tcc -c command.c
"""

, .

, , , Python? ? , Python Python ast:

>>> print('\\t')        # remember: we have to escape tab-escape with single quotes
\t
>>> import ast
>>> print(ast.dump(ast.parse('"""hello  world"""')))
Module(body=[Expr(value=Str(s='hello\tworld'))])
>>> print(ast.dump(ast.parse('"""hello\\tworld"""')))
Module(body=[Expr(value=Str(s='hello\tworld'))])
>>> ast.dump(ast.parse('"""hello        world"""')) == ast.dump(ast.parse('"""hello\\tworld"""'))
True

, Python .

:

>>> print(ast.dump(ast.parse('r"""hello\\tworld"""')))
Module(body=[Expr(value=Str(s='hello\\tworld'))])

, ( ).

+1

All Articles