当用三引号“”“写一个字符串时,字面上为新行或制表符添加\ n或\ t的区别是什么,只是按照你想要的方式在引号内写出来? 例如:
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? """
有一种方式首选吗?
答案 0 :(得分:3)
记住最好是明确而不是隐含。使用特定的\t
和\n
不会留下任何假设。
答案 1 :(得分:1)
标签不可见,因此\t
更可取。但是如果你使用原始字符串文字r"""\t"""
,则\t
是两个字符而不是一个字符(在这种情况下它不是一个制表符)。此外,三重引号内的选项卡没有任何具体内容,普通引号(""
和''
)的行为相同。
答案 2 :(得分:1)
口译员没有区别。不同之处在于您和其他程序员:使用\t
您确定它是一个制表符。使用文件中的真实列表,它可能是4个空格或制表。
正如@IanAuld所说,并且如 Python 中所述,
明确比隐含更好。
所以我更喜欢\t
。
答案 3 :(得分:1)
正如其他答案所指出的那样,\t
在浏览代码时显而易见,所以请使用它!而您可能很容易将文字标签误认为一个或多个空格(特别是如果制表符恰好只占用一个字符)。
这并不是说你可能永远不会包含文字标签。想象一下,您在Python源代码中嵌入了多行Makefile代码段。诀窍是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在ast module中公开了一个Python语言解析器:
>>> 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'))])
我们看到表示方式不同(正如预期的那样)。