2013-06-26 29 views
1

我正在運行python 3的教程,在打印時出現奇怪的行爲。例如:意外的打印行爲Python 3

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'] 

如何避免在打印輸出的第二和第三列出了行開頭的額外空間?

回答

3

使用sep = ''

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

sep默認值是一個空格:

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

幫助上printprint(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. 
6

只要指定'\n'作爲分隔符,這將備用你在每一件物品上添加一條換行符:

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