2014-03-01 3654 views
12

我在嘗試找到答案時遇到了一些麻煩。我想知道語法sep=""\t的含義。我發現了一些關於它的信息,但我不太明白使用語法的目的是什麼。我正在尋找解釋它的作用以及何時/爲什麼要使用它。print(... sep ='',' t')是什麼意思?

正在使用的sep=''一個例子:

print('Property tax: $', format(tax, ',.2f'), sep='') 

回答

19

在函數調用的上下文sep=''設置命名參數sep爲空字符串。請參閱print() function; sep是打印時在多個值之間使用的分隔符。默認值是一個空格(sep=' '),此函數調用可確保在Property tax: $和格式化的tax浮點值之間沒有空格。

比較以下三個print()調用的輸出看出差別

>>> print('foo', 'bar') 
foo bar 
>>> print('foo', 'bar', sep='') 
foobar 
>>> print('foo', 'bar', sep=' -> ') 
foo -> bar 

所有這一切改變的是sep參數值。

\tin a string literaltab character, horizontal whitespace, ASCII codepoint 9的轉義序列。

\t比實際的製表符更容易閱讀和輸入。請參閱table of recognized escape sequences以瞭解字符串文字。

使用空格或標籤\t作爲打印分離器示出的區別:

>>> print('eggs', 'ham') 
eggs ham 
>>> print('eggs', 'ham', sep='\t') 
eggs ham 
+0

打印( '財產稅:$',格式(稅, '.2f '),九月='') 將是一個線的一個例子代碼用於。 – krona

+0

@krona:'sep ='''與'sep「」'不是一回事。請參閱['print()'函數文檔](http://docs.python.org/3/library/functions.html#print);該代碼將'sep'關鍵字參數設置爲空字符串。 –

+0

@Noumenon:在Python 2中,使用'from __future__ import print_function';這不僅限於Python 3.問題是使用'print()'作爲一個函數,因此我對這種情況進行了裁剪。 –

0
sep=''

忽略空白。 看到代碼到understand.Without sep=''

from itertools import permutations 
s,k = input().split() 
for i in list(permutations(sorted(s), int(k))): 
    print(*i) 

輸出:使用sep='' 的代碼和輸出

HACK 2 
A C 
A H 
A K 
C A 
C H 
C K 
H A 
H C 
H K 
K A 
K C 
K H 

from itertools import permutations 
s,k = input().split() 
for i in list(permutations(sorted(s), int(k))): 
    print(*i,sep='') 

輸出:

HACK 2 
AC 
AH 
AK 
CA 
CH 
CK 
HA 
HC 
HK 
KA 
KC 
KH