网站 演示代码,网站svg使用,深圳微信网站公司,成都包装设计公司哪家好format用法
相对基本格式化输出采用‘%’的方法#xff0c;format()功能更强大#xff0c;该函数把字符串当成一个模板#xff0c;通过传入的参数进行格式化#xff0c;并且使用大括号‘{}’作为特殊字符代替‘%’使用方法由两种#xff1a;b.format(a)和format(a,b) fo…format用法
相对基本格式化输出采用‘%’的方法format()功能更强大该函数把字符串当成一个模板通过传入的参数进行格式化并且使用大括号‘{}’作为特殊字符代替‘%’使用方法由两种b.format(a)和format(a,b) format 函数可以接受不限个参数位置可以不按顺序
1、不带编号即“{}”
print({} {}.format(hello,world))# 不设置指定位置按默认顺序
hello world
2、带数字编号可调换顺序即“{1}”、“{2}”
print({0} {0}.format(hello,world))
hello hello
print({0} {1}.format(hello,world))
hello world
print({1} {0}.format(hello,world))
world hello
print({0} {0}.format(hello))
hello hello
3、带关键字即“{a}”、“{tom}”
print({x} {y}.format(xhello,yworld))
hello world
4、通过映射 list
list a_list [chuhao,20,china]
print(my name is {0[0]},from {0[2]},age is {0[1]}.format(a_list))
my name is chuhao,from china,age is 20
5、通过映射dict
dict b_dict {name:chuhao,age:20,province:shanxi}
print(my name is {name}, age is {age},from {province}.format(**b_dict))
my name is chuhao, age is 20,from shanxi
6、传入对象
class AssignValue(object): def __init__(self, value): self.value value
my_value AssignValue(6)
print(value 为: {0.value}.format(my_value))
value 为: 6