2015-01-21 37 views
1

我如何使用string.format()的方式使得:與Python的使用的String.Format陣列()

line = 'first {0}, second {1}' 
print(line.format([1,2])) 

將打印first 1 second 2

+1

需要注意的是明確的編號格式字段是隻需要在Python 2.6。所有現代版本的Python都會爲你做,所以你只需要:'line ='first {},second {}'' – iCodez 2015-01-21 03:26:24

回答

4

您可以unpack the list

>>> line = 'first {0}, second {1}' 
>>> l = [1, 2] 
>>> print(line.format(*l)) 
first 1, second 2 
+0

命名變量'l'通常最好避免以避免'I','l'之間的混淆。和'1' – Holloway 2015-02-25 10:49:22

+0

@Trengot這是一個很好的觀點,謝謝! – alecxe 2015-02-25 13:16:44