字符串的格式化

1、%s  表示占位符

如name = "诸葛孔%s" %"”明" 就等于name = "诸葛孔明"

 

 

 

2、%d  与%s用法一样,只不过%s用于字符串,%d用于数字

如name = " 鲁班%d号" %1

即:name = "鲁班1号"

 

 

 

3、%%  第一个%表示转义

 

 

 

4、join的使用

 

 

 

5、format函数用法

format用法

 相对基本格式化输出采用‘%’的方法,format()功能更强大,该函数把字符串当成一个模板,通过传入的参数进行格式化,并且使用大括号‘{}’作为特殊字符代替‘%’

使用方法由两种:b.format(a)和format(a,b)。

1、基本用法

  (1)不带编号,即“{}”

  (2)带数字编号,可调换顺序,即“{1}”、“{2}”

  (3)带关键字,即“{a}”、“{tom}”

>>> print('{} {}'.format('hello','world')) # 不带字段
hello world
>>> print('{0} {1}'.format('hello','world')) # 带数字编号
hello world
>>> print('{0} {1} {0}'.format('hello','world')) # 打乱顺序
hello world hello
>>> print('{1} {1} {0}'.format('hello','world'))
world world hello
>>> print('{a} {tom} {a}'.format(tom='hello',a='world')) # 带关键字
world hello world

2、进阶用法

(1)< (默认)左对齐、> 右对齐、^ 中间对齐、= (只用于数字)在小数点后进行补齐

(2)取位数“{:4s}”、"{:.2f}"等

>>> print('{} and {}'.format('hello','world')) # 默认左对齐
hello and world
>>> print('{:10s} and {:>10s}'.format('hello','world')) # 取10位左对齐,取10位右对齐
hello and world
>>> print('{:^10s} and {:^10s}'.format('hello','world')) # 取10位中间对齐
hello and world
>>> print('{} is {:.2f}'.format(1.123,1.123)) # 取2位小数
1.123 is 1.12
>>> print('{0} is {0:>10.2f}'.format(1.123)) # 取2位小数,右对齐,取10位
1.123 is 1.12

 

 
posted on 2020-12-08 22:08  坚持_学习  阅读(102)  评论(0编辑  收藏  举报