首页 > 解决方案 > Python \n 在输出之间给出两个空格, \t 给出一个

问题描述

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

fav_num = {
    'rachel':'blue',
    'hannah':'green',
}
print(fav_num['rachel'])
print(fav_num['hannah'])
#6-3
coding_glossary = {
    'list':'mutable type where you can store info',
    'tuple':'immutable type similar to list',
    'string':'simple line of code'
}
print('\t')
print('Some things I learned so far: \n')
print('What a list is:')
print(coding_glossary['list'])

输出是:

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

标签: python

解决方案


python 的内置打印函数隐式地将 '\n' 作为结束字符。

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

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

因此,每次运行时都会隐式打印print()一个 ' \n' 字符,除非您通过传递end=给它来覆盖该行为。(end=''例如)


推荐阅读