意外的打印行为3

2022-12-01 05:35:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在浏览python3的教程,在打印时遇到了一些奇怪的行为。例如:

print ("\nUnpickling lists.")
pickle_file = open("pickles1.dat", "rb")
variety = pickle.load(pickle_file)
shape = pickle.load(pickle_file)
brand = pickle.load(pickle_file)
print (variety,"\n",shape,"\n",brand)
pickle_file.close()

给了我:

Unpickling lists.
['sweet', 'hot', 'dill'] 
 ['whole', 'spear', 'chip'] 
 ['Claussen', 'Heinz', 'Vlassic']

如何避免在第二个和第三个列表的打印输出行的开头有多余的空间?你知道吗


Tags: load教程openpicklelistspython3datfileprintshapebrandrbvarietypickles1nunpickling
2条回答

使用sep = ''

print (variety,"\n",shape,"\n",brand, sep = '')

sep的默认值是单个空格:

>>> print('a','b')
a b
>>> print('a','b', sep ='')
ab

有关print的帮助:print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

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.
flush: whether to forcibly flush the stream.

只需指定'\n'作为分隔符,就可以在每个项目之间添加一个换行符:

print(variety, shape, brand, sep='\n')