Python在输出之间\n给出两个空格,\t给出一个空格

Python在输出之间\n给出两个空格,\t给出一个空格,python,Python,我不明白为什么在代码之间输入一个空格时,\t会在“绿色”和“到目前为止我学到的一些东西:”输出之间留出一行空格。当我使用\n时,它在两者之间提供两个空格。对于\t和\n,空间不应该相同吗?我知道\t是制表符,\n是新行。但我不明白\n两个空格之间是怎么回事 代码是: 输出为: blue green Some things I learned so far: What a list is: mutable type where you can store info Process fini

我不明白为什么在代码之间输入一个空格时,\t会在“绿色”和“到目前为止我学到的一些东西:”输出之间留出一行空格。当我使用\n时,它在两者之间提供两个空格。对于\t和\n,空间不应该相同吗?我知道\t是制表符,\n是新行。但我不明白\n两个空格之间是怎么回事 代码是:

输出为:

blue
green

Some things I learned so far: 

What a list is:
mutable type where you can store info

Process finished with exit code 0

您的代码可以等效地编写:

#
print()
print(‘Some things I learned so far:’)
print()
#
python的结尾字符为“\n”

打印*对象,sep='',end='\n',file=sys.stdout,flush=False:

将对象打印到文本流文件中,以sep分隔,后跟end。sep、end、file和flush(如果存在)必须作为关键字参数提供


因此,每次运行print时,都会隐式打印一个“\n”字符,除非通过向其传递end=来重写该行为。like end=example

默认情况下,打印在末尾添加新行,要修改此行为,可以使用end设置end参数=

例如:

print("this will use 2 lines \n")
print("this will use 1 line")
print("this will use 1 line \n", end="")

默认情况下,打印转到下一行。试一试

print(" ",end = "")
这样您可以更清楚地看到“\t”

此外,tab跳到下一个块。一个区块通常有4个空格。 试试这个,然后注意到。是:

print("\t", end=".\n")
print("A\t", end=".\n")
print("ABC\t", end=".\n")
print("ABCD\t", end=".\n")
语句print'\t'正在打印一个选项卡,然后返回下一行,因为默认的print函数会自动添加一个换行符。所以你看不到账单,但它在那里。在打印的字符串末尾添加\n时,除了默认的换行符外,还会添加换行符

要删除默认的换行符,请指定打印函数的“end”参数:

打印'abcd\n',结束=

这将只包括一行返回。

因为print在每个输出的末尾都会给出一个“\n”字符串,所以命令print“\n”会给出命令行字符串“\t\n”

有关更多详细信息,请参阅以下详细说明的帖子

\n字符是新行字符,打印时会转到新行

但打印功能最终也有了新的线条 默认情况下,在打印函数结束集中\n printend=\n

如果您尝试打印具有覆盖结尾的内容,则它将如下所示

print("hello", end="")  # here cursor will not change self position because end=""
print("world")  # here cursor goes to new line because end by default is "\n"
地狱世界

\t是用于打印选项卡的字符

上述代码的输出将保存表格

current number is    0
current number is    1
current number is    2
current number is    3
current number is    4
current number is    5
current number is    6
current number is    7
current number is    8
current number is    9
current number is    10
current number is    11
current number is    12
current number is    13
current number is    14
current number is    15
current number is    16
current number is    17
current number is    18
current number is    19

您可以找到其他可以在您的程序中使用的魔法字符

“打印”在您要求打印的内容末尾添加了自己的新行。
for i in range(20):
    print("current number is\t", i)
current number is    0
current number is    1
current number is    2
current number is    3
current number is    4
current number is    5
current number is    6
current number is    7
current number is    8
current number is    9
current number is    10
current number is    11
current number is    12
current number is    13
current number is    14
current number is    15
current number is    16
current number is    17
current number is    18
current number is    19