191124 python format 字符串格式化

女生的网名这么多〃 提交于 2019-11-30 08:49:02

format是什么?

format()函数是用于字符串类型格式化的方法,调用format()函数方法会返回一个新的字符串,参数从0开始编号

# 基本使用格式
"【模板字符串】".format(【逗号分隔的参数】)
# 按顺序输出格式化数据
>>> "{} {}".format("hello","python")
'hello python'
>>> 

# 按序列号下标输出格式化数据
>>> "{1} {0}".format("hello","python")
'python hello'
>>> 

# 通过键来输出格式化数据


填充作用

除了参数外的字符采用什么方式,默认采用空格。

# 指定填充的格式
>>> mystr = "hello python"
>>> len(mystr)
12
>>> "{0:#^30}".format(mystr)
'#########hello python#########'
>>> "{0:-^30}".format(mystr)
'---------hello python---------'

# 指定总长度,不指定字符使用空格填充
>>> mystr = "hello python"
>>> len(mystr)
12
>>> "{0:^30}".format(mystr)
'         hello python         '
>>> 

# 字符串总长度12,指定长度为13,因此往右偏移一个
>>> "{0:>13}".format(mystr)
' hello python'
>>> "{0:<13}".format(mystr)
'hello python '
>>> 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!