项目被添加到数组中,但我需要它们以特定格式打印。 例如:
[('Curly',35,'New York')]
打印为:
姓名:Curly Aged:35岁,住在纽约。
示例代码:
stooges = [('Curly',35,'New York'),('Larry',33,'Pennsylvania'),('Moe',40,'New York')]
print (stooges)
答案 0 :(得分:4)
stooges = [('Curly',35,'New York'),('Larry',33,'Pennsylvania'),('Moe',40,'New York')]
for t in stooges:
print('Name: %s Aged: %d and lives in %s' % t)
Name: Curly Aged: 35 and lives in New York Name: Larry Aged: 33 and lives in Pennsylvania Name: Moe Aged: 40 and lives in New York
答案 1 :(得分:2)
for stooge in stooges:
print("Name: {0} Age: {1}, and lives in {2}".format(stooge[0],stooge[1],stooge[2])
这使用了string.format()
功能,它功能非常强大,可以进行多种不同类型的格式化。
字符串的{0}
部分用于将第一个参数引用到.format()
,另外两个用于.format()
以下是文档
的快速示例>>> '{0}, {1}, {2}'.format('a', 'b', 'c')
'a, b, c'