python格式化字符串(1):format()用法详解
2019-04-08 15:12
453 查看
作者:IT小样
1、代码示例
Python中使用format()函数来格式化字符串,先上一个代码示例:
format_temp = "hello,{},welcome to {}!" format_temp.format("lily","China")
代码输出结果为:hello,lily,welcome to China!
2、使用讲解
字符串模板.format(格式1,格式2,…,格式N),从上面的代码示例中可以看出,在字符串模板中,以{}来表示需要格式化的地方,而在format参数中以“,”来分隔参数。
2.1、格式化位置排序
在字符串模板中,若没有标明格式化的位置,会自动对出现的{}的位置进行排序,从0开始排序,当然也可以在字符串模板中对其进行排序,示例如下:
#示例1,自动排序对位 format_temp = "hello,{},welcome to {}!" format_temp.format("lily","China")#示例2,手动排序 format_temp = "hello,{1},welcome to {0},nice to meet you,{1}!" format_temp.format("Tokeyo","Ben")
两段分别输出:
hello,lily,welcome to China!
hello,Ben,welcome to Tokeyo,nice to meet you,Ben!
2.2、格式控制信息
在字符串模板{}中,还可以设置输出的格式化字符串的格式,如下:
: | 填充 | 对齐 | 宽度 | , | .精度 | 类别 |
---|---|---|---|---|---|---|
用来填充剩余长度的符号 | 对齐方式:<,左对齐;>,右对齐;^,居中对齐 | 输出的位数 | 千分位分隔符 | 浮点数小数部分精度或者字符串最大长度 | 整数类型B,c,d,o,x,X以及浮点数类型e,E,f,% |
示例:
"hello,{0:*>10.3}”,welcome to {1}!".format("lily","China")
输出见图:
2.3、注意事项
如果想输出“{”时,需要用“{{”代替,如果想输出“}”时,需要用“}}”代替。
注:Python3.6之后,可以采用f-string方式格式化字符串,用法简介见链接:f-string格式化字符串
相关文章推荐
- python,格式化字符串函数.format()的用法
- 浅析python3字符串格式化format()函数的简单用法
- Python--format 函数格式化字符串的用法
- Python - 格式化(format())输出字符串 详解 及 代码
- Python - 格式化(format())输出字符串 详解 及 代码
- Python - 格式化(format())输出字符串 详解 及 代码
- python3字符串格式化format()函数的简单用法
- python格式化字符串format的用法
- python 字符串格式化 ( 百分号 & format )
- Python中用format函数格式化字符串的用法
- Python中用format函数格式化字符串的用法
- Python 字符串格式化输出(format/printf)
- python的格式化输出(format,%)实例详解
- Python中用format函数格式化字符串的用法
- Python .format(),%格式化时,对字符串编码方式的影响
- Python中用format函数格式化字符串的用法
- Python中用format函数格式化字符串的用法
- Python中用format函数格式化字符串的用法
- python笔记---字符串格式化函数format
- python知识点5之字符串格式化 (%和format)