简体   繁体   English

意外的打印行为Python 3

[英]Unexpected print behaviour Python 3

I'm running through a tutorial for python 3 and I'm getting strange behaviour on printing. 我正在阅读有关python 3的教程,并且在打印时遇到了奇怪的现象。 for example: 例如:

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()

gives me: 给我:

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

How do I avoid the extra space at the beginning of the lines of print output for the second and third lists? 如何避免第二个和第三个列表的打印输出行开头出现多余的空间?

只需将'\\n'指定为分隔符,即可避免在每个项目之间添加换行符:

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

Use sep = '' : 使用sep = ''

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

Default value of sep is a single space: sep默认值为一个空格:

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

help on print : print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False) 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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM