2013-05-06 51 views
1

我創建了一個方法來打印一些東西:打印打印一些額外的跡象

def my_print(*str1): 
    print '---------------' 
    print str1 
    print '---------------' 


my_print('1fdsfd %s -- %s' % (12, 18)) 

這給了我

--------------- 
('1fdsfd 12 -- 18',) 
--------------- 

爲什麼我有這些額外的()甚至,和我該怎麼辦擺脫他們?

+3

爲什麼在'my_print'函數定義中有星號? – Volatility 2013-05-06 10:19:00

回答

3

的原因是由於在*str1被轉換成my_print函數內的元組,則可以刪除該*或使用print str1[0]

當在函數定義中使用*時,它將起到收集器的作用,並收集傳遞給函數的所有位置參數。

>>> def func(*a): 
...  print type(a) 
...  print a 
...  
>>> func(1) 
<type 'tuple'> 
(1,) 
>>> func(1,2,3) 
<type 'tuple'> 
(1, 2, 3) 

工作代碼的版本:

def my_print(str1): 
    print '---------------' 
    print str1 
    print '---------------' 


my_print('1fdsfd %s -- %s' % (12, 18)) 

或:

def my_print(*str1): 
    print '---------------' 
    print str1[0] 
    print '---------------' 


my_print('1fdsfd %s -- %s' % (12, 18)) 
+0

可能是OP認爲做'打印a,b,c'或't = a,b,c; print t'會產生相同的結果,但python2中並不是這種情況,因爲'print'是一個具有自己語法的語句。 – Bakuriu 2013-05-06 10:30:12

0

取出*和使用str.format()代替:

mytuple = (12, 18) 
my_print('1fdsfd {0} -- {1}'.format(*mytuple)) # I've used the * here to unpack the tuple. 

正如其他有POI它將str1轉換成元組。

+0

爲什麼不只是'my_print('1fdsfd {0} - {1}'。format(12,18))'? – Volatility 2013-05-06 10:22:46

+0

@Volatility我假設輸入是一個元組 – TerryA 2013-05-06 10:22:58

+0

然後使用'my_print('1fdsfd {0} - {1}'.format(* input_tuple))' – Volatility 2013-05-06 10:24:06

0

由於您使用splat(*)運算符解包給您的函數的所有參數,因此您將得到一個保存爲str1的參數元組,例如。

>>> my_print('a', 'b') 
--------------- 
('a', 'b') 
--------------- 

然後你只是打印參數的元組,就好像你不需要圖示,因爲你只有str1所以只是將其刪除,它工作正常。