当前位置:首页 > 日记本 > 正文内容

pythonstr.format()详解格式化字符串介绍

zhangchap3年前 (2021-09-13)日记本361

前序:format是python2.6新增的一个格式化字符串的方法,相对于老版的%格式方法,它有很多优点。

    不需要理会数据类型的问题,在%方法中%s只能替代字符串类型
    单个参数可以多次输出,参数顺序可以不相同
    填充方式十分灵活,对齐方式十分强大

    官方推荐用的方式,%方式将会在后面的版本被淘汰


format填充字符串

一 填充

1.通过位置来填充字符串

print('hello {0} i am {1}'.format('world','python')) # 输入结果:hello world i am 
python
print('hello {} i am {}'.format('world','python') ) #输入结果:hello world i am 
python
print('hello {0} i am {1} . a now language-- 
{1}'.format('world','python')
# 输出结果:hello world i am python . a now language-- python

foramt会把参数按位置顺序来填充到字符串中,第一个参数是0,然后1 ……

也可以不输入数字,这样也会按顺序来填充

同一个参数可以填充多次,这个是format比%先进的地方

2.通过key来填充

list=['world','python']
print('hello {names[0]}  i am {names[1]}'.format(names=list))# 输出结果:hello world  i am python
print('hello {0[0]}  i am {0[1]}'.format(list)) #输出结果:hello world  i am python

3.通过列表填充

list=['world','python']
print('hello {names[0]}  i am {names[1]}'.format(names=list))# 输出结果:hello world  i am python
print('hello {0[0]}  i am {0[1]}'.format(list)) #输出结果:hello world  i am python

4.通过字典填充

dict={‘obj’:’world’,’name’:’python’} 
 print(‘hello {names[obj]} i am {names[name]}’.format(names=dict)) # hello world i am python

注意访问字典的key,不用引号的

5.通过类的属性填充

class Names():
    obj='world'
    name='python'

print('hello {names.obj} i am {names.name}'.format(names=Names))#输入结果hello world i am python

6.使用魔法参数

args = [‘,’,’inx’]
kwargs = {‘obj’: ‘world’, ‘name’: ‘python’}
print(‘hello {obj} {} i am {name}’.format(*args, **kwargs))#输入结果:hello world , i am python

注意:魔法参数跟你函数中使用的性质是一样的:这里format(*args, **kwargs)) 等价于:format(‘,’,’inx’,obj = ‘world’,name = ‘python’)

format 格式转换


数字格式输出描述
3.1415926{:.2f}3.14保留小数点后两位
3.1415926{:+.2f}3.14带符号保留小数点后两位
-1{:+.2f}-1带符号保留小数点后两位
2.71828{:.0f}3不带小数
1000000{:,}1,000,000以逗号分隔的数字格式
0.25{:.2%}25.00%百分比格式
1000000000{:.2e}1.00E+09指数记法
25{0:b}11001转换成二进制
25{0:d}25转换成十进制
25{0:o}31转换成八进制
25{0:x}19转换成十六进制
5{:0>2}05数字补零(填充左边, 宽度为2)
5{:x<4}5xxx数字补x (填充右边, 宽度为4)
10{:x^4}x10x数字补x (填充两边,优先左边, 宽度为4)
13{:10}13右对齐 (默认, 宽度为10)
13{:<10}13左对齐 (宽度为10)
13{:^10}13中间对齐 (宽度为10)

b、d、o、x分别是二进制、十进制、八进制、十六进制。

其它用法

1.转义“{}”

print('{{hello}} {{{0}}}'.format('world')) #输出结果:{hello} {world}

跟%中%%转义%一样,format中用 { 来转义{ ,用 } 来转义 }


2.format作为函数变量

name = 'InX'
hello = 'hello,{} welcome to python world!!!'.format #定义一个问候函数
hello(name) #输入结果:hello,inx welcome to python world!!!


3.格式化datetime

from datetime import datetime
now=datetime.now()
print(now)
print ('{:%Y-%m-%d %X}'.format(now))

4.{}内嵌{}

print('hello {0:>{1}} '.format('world',10)) ##输出结果:hello      world

从最内层的{}开始格式化

5.叹号的用法

print("{!s}国".format("中")) #输出结果:中国
print("{!a}国".format("中")) #输出结果:"\u4e2d"国
print("{!r}国".format("中")) #输出结果:"中"国

!后面可以加s r a 分别对应str() repr() ascii() 作用是在填充前先用对应的函数来处理参数
差别就是repr带有引号,str()是面向用户的,目的是可读性,repr()是面向Python解析器的,返回值表示在python内部的含义,ascii (),返回ascii编码

原文链接:https://blog.csdn.net/u014770372/article/details/76021988



分享给朋友:

相关文章

CDN下 Nginx开启PC/M识别跳到对应的域名下访问,css/js死循环问题

背景: 新做了一个网站:   服务器操作系统:Linux;   WEB服务器版本:nginx/1.16.1; 问题:...

宝塔重启服务器后,Redis就启动不了解决方案

宝塔重启服务器后,Redis就启动不了解决方案

1.更改权限 chown -R redis.redis /www/server/redis/ 2.设置持久化...

Nginx+PHP,PHP如何优化配置?

具体修改FPM配置文件参数: 若你的php日志出现: WARNING: [pool www] seems busy (you may need to increase pm.sta...

python 函数 开启多线程示例

from threading import Thread def readfile(queue:Queue):    &nbs...

python补全网址代码示例

from urllib.parse import urljoin absurl = urljoin(backend,url) #backend:根...

python读取txt文件放到Queue队列

from queue import Queue with open('kw.txt',encoding='utf-8')&nb...

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。