1. '%'字符串格式化html
#方法一: '%' num = 10 print('--the number is %d--'%num) #output: "--the number is 10--" print('the float number is %f'%-3.14) #output: "the float number is -3.140000",自动格式 print('the float number is %6.3f'%-3.14) #output: "the float number is -3.140" #此时6.3的6表示宽度(包括正负号和小数点),3表示精度(也就是小数点位数,浮点型时) print('the float number is %-9.3d'%-3) #output: "the float number is -003 " #此时-9.3d,d表示整型,此时3表示显示的数字宽度,不足的补零,9表示整个字符宽度,不足的补空格 print('the float number is %09.3f'%-3.14) #output: "the float number is -0003.140" #浮点型,此时09.3表示精度为3位,宽度为9,不足的在前面补零 print('the float number is %-9.3f'%-3.14) #output: "the float number is -3.140 " #此时-9.3表示精度为3位,宽度为9,不足的在后面补空格(由于没有指定补零),最前面的负号'-'表示左对齐
2. format字符串格式化python
#方法二: format print("what is your {}: {}!".format('name','Jack')) # output: "what is your name: Jack!" #依次对应前面的括号,当括号内没有值时 print('what is your {flag}?--- {1},and {0}? ---{myname}'.format(flag='name','you','Bob',myname='Lily')) # SyntaxError: positional argument follows keyword argument,遵照python的参数赋值顺序,关键字参数应该在后面 print('what is your {flag}?--- {1},and {0}? ---{myname}'.format('you','Bob',flag='name',myname='Lily')) #output: "what is your name?--- Bob,and you? ---Lily",遵照python赋值顺序 print('what is your {flag}?--- {1},and {0}? ---{myname}'.format('you','Bob','name','Lily')) # KeyError: 'flag',由于前面的格式写了'flag',可是后面没有找到 print('what is your {2}?--- {1},and {0}? ---{3}'.format('you','Bob','name','Lily')) #output: "what is your name?--- Bob,and you? ---Lily",以format中元组的索引赋值 print('what is your {1[0]}--- {0[1]},and {0[0]} ---{1[1]}'.format(('you','Bob'),('name','Lily'))) #output: "what is your name--- Bob,and you ---Lily",元组嵌套元组的索引赋值
3. format带精度,对齐,补足位spa
## ^、<、>分别是居中对齐、左对齐、右对齐 print('{0}+{1}={2:$>6}'.format(2.4,3.1,5.5)) #"2.4+3.1=$$$5.5",>表示右对齐,6位宽度,$用于补足空位 print('{0}+{1}={2:$^6}'.format(2.4,3.1,5.5)) #"2.4+3.1=$5.5$$",^表示居中对齐 print('{0}+{1}={2:$<6}'.format(2.4,3.1,5.5)) #"2.4+3.1=5.5$$$",<表示左对齐 print('{0}+{1}={2:$<6.2f}'.format(2.4,3.1,5.5)) #"2.4+3.1=5.50$$",6.2f表示宽6位,精度是2位,浮点型 print('{0:$<6.2f}'.format(5.5)) #或者 print('{:$<6.2f}'.format(5.5)) #"5.50$$",只有一个参数时
4. format的字典传递关键字参数格式化、列表传递位置参数格式化3d
dict_para = {'flag':'question','name':'Jack'} print("what is your {flag}: {name}!".format(**dict_para)) #"what is your question: Jack!",用字典传递参数,'**'用于收集关键字参数 list_para = ['question','Jack'] print("what is your {}: {}!".format(*list_para)) # "what is your question: Jack!",用列表传递参数,'*'用于收集参数
参考:code