【1.21】format的使用,字符串 的 format 方法

 * 是列表,* * 是字典
1、自己编写时就要做到,一 一对应输入,可多不能少  元组方式
tpl = "i am {}, age {}, {}".format("seven", 18, 'alex')
 
2、自己编写时就要做到,一 一对应输入,可多不能少,列表方式  用单 星 号
tpl = "i am {}, age {}, {}".format(*["seven", 18, 'alex'])
 
3、可以不对应输入,可多不能少,定义取值位置  元组
tpl = "i am {0}, age {1}, really {0}".format("seven", 18)
 
4、、可以不对应输入,可多不能少,定义取值位置 列表
tpl = "i am {0}, age {1}, really {0}".format(*["seven", 18])
  
5、定义key values 的字典来输入
tpl = "i am {name}, age {age}, really {name}".format(name="seven", age=18)
 
6、 定义key values 的字典来输入
tpl = "i am {name}, age {age}, really {name}".format(**{"name": "seven", "age": 18})
 
7、列表嵌套输入和调用
tpl = "i am {0[0]}, age {0[1]}, really {0[2]}".format([1, 2, 3], [11, 22, 33])
  
8、数据类型的方式来判断取值,:s 是字符串,:d是整数 , :f是浮点数的方式
tpl = "i am {:s}, age {:d}, money {:f}".format("seven", 18, 88888.1)
  
9、同八,一个元组一个是列表
tpl = "i am {:s}, age {:d}".format(*["seven", 18])
 
10、定义变量和数据类型 
tpl = "i am {name:s}, age {age:d}".format(name="seven", age=18)
 
11、定义字典 变量和类型
tpl = "i am {name:s}, age {age:d}".format(**{"name": "seven", "age": 18})
 
12、接收数据后按照  字符串的定义的数据类型进行转化 ,一一对应,
tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2)
 
tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2)
 
13、同 12,但是定义了取值的位置 0 ,也可以定义变量名字 如下面的两个
tpl = "numbers: {0:b},{0:o},{0:d},{0:x},{0:X}, {0:%}".format(15)
 
tpl = "numbers: {num:b},{num:o},{num:d},{num:x},{num:X}, {num:%}".format(num=15)
posted @ 2016-03-15 16:21  科学小怪癖  阅读(244)  评论(0)    收藏  举报