标签:range out form dex err 必须 job index 组元
python中使用format格式化字符串
通过位置格式化
info = ‘my name is {0} and i am {1} old , job is {0} ‘ print(info.format(‘xxx‘,18)) >>>my name is xxx and i am 18 old , job is xxx
如果format后的元组内的元素个数少于要格式化字符的个数,则必须在要格式化的字符处添加元组元素的索引位置。否则会抛出异常。
info = ‘my name is {} and i am {} old , job is {} ‘ #格式化3个字符 print(info.format(‘xxx‘,18)) #只有两个元素 >>>IndexError: tuple index out of range #报错
如果要格式化的字符个数少于元组元素的数量,则会顺序添加
info = ‘my name is {} and i am {} old ‘ #格式化2个字符 print(info.format(‘xxx‘,18,‘454‘,‘abc‘)) # 元组内包含4个元素 >>>my name is xxx and i am 18 old #顺序添加 ,多余的忽略
通过key来格式化
info = ‘my name is {name} and i am {age} old , job is {work} ‘ print(info.format(name=‘xxx‘,age=18,work=‘IT‘)) >>>my name is xxx and i am 18 old , job is IT
通过下标格式化
data = [‘xxx‘,18,‘IT‘] info = ‘my name is {data[0]} and i am {data[1]} old , job is {data[2]} ‘ print(info.format(data=data)) >>>my name is xxx and i am 18 old , job is IT info = ‘my name is {0[0]} and i am {0[1]} old , job is {0[2]} ‘ print(info.format(data)) >>>my name is xxx and i am 18 old , job is IT
通过字典的key
data = {‘name‘:‘xxx‘,‘age‘:18,‘job‘:‘IT‘} info = ‘my name is {aaa[name]} and i am {aaa[age]} old , job is {aaa[job]} ‘ print(info.format(aaa=data)) >>>my name is xxx and i am 18 old , job is IT
#其他方法暂略。。。
标签:range out form dex err 必须 job index 组元
原文地址:https://www.cnblogs.com/romacle/p/10486722.html