2 qq 26097991 qq_26097991 于 2017.09.04 18:19 提问

关于python索引的问题

具体代码如下:
age = 20
name = 'Swaroop'
print('{0} was {1} years old when he wrote this book'.format(name, age))
print('Why is {0} playing with that python?'.format(name))
输出:
$ python str_format.py Swaroop was 20 years old when he wrote this book Why is Swaroop playing with that python?

我想问一下python的索引从0开始 那么0不应该是age 1不应该是name吗?

2个回答

oyljerry
oyljerry   Ds   Rxr 2017.09.05 20:39

0,1是format的参数占位符,就是表示第一个,第二个参数。也就是name,age来替换对应位置字符串

WLY19930402
WLY19930402   2017.09.07 10:58

这个主要看foemat后面的顺序,你把name放在前面,那么name就是0,你可以把name 和age 的位置换一下,
age = 20
name = 'Swaroop'
print('{0} was {1} years old when he wrote this book'.format( age,name))
print('Why is {0} playing with that python?'.format(age))看看结果。
这是format函数灵活的地方,format(v1,v2,...)v1总是对应第一个{0},v2对应{1},以此类推。

Csdn user default icon
上传中...
上传图片
插入图片