当前位置: 首页 > news >正文

中国建设银行网站首页 定投中国站长之家

中国建设银行网站首页 定投,中国站长之家,中国住房城乡建设部网站首页,比较好的 网站统计系统 php源码Python格式化字符串的4中方式 一、%号 二、str.format(args) 三、f-Strings 四、标准库模板 五、总结四种方式的应用场景’ 一、%号占位符 这是一种引入最早的一种,也是比较容易理解的一种方式.使用方式为: 1、格式化字符串中变化的部分使用占位符 2、…

Python格式化字符串的4中方式
一、%号
二、str.format(args)
三、f-Strings
四、标准库模板
五、总结四种方式的应用场景’

一、%号占位符

这是一种引入最早的一种,也是比较容易理解的一种方式.使用方式为:

1、格式化字符串中变化的部分使用占位符
2、变量以元组形式提供
3、变量与格式化字符串之间以%连接

1、格式的字符串(即%s)与被格式化的字符串(即传入的值)必须按照位置一一对应

ps:当需格式化的字符串过多时,位置极容易搞混

例如

a = 'zhangsan'
b = 'lisi'
print('%s eated %s' % (a, b))  # zhangsan eated lisi
print("%s asked %s to do something" % ("zhangsan", 'lisi'))  # zhangsan asked lisi to do something

2、可以通过字典方式格式化,打破了位置带来的限制与困扰

print("我的名字是%(name)s,我的年龄是%(age)s" % {"name": 'zhangsan', "age": "list"})  # 我的名字是zhangsan,我的年龄是listkwargs = {"name": "zhangsan", "age": 18}
print("my name is %(name)s, my age is %(age)s" % kwargs)  # my name is zhangsan, my age is 18

二、str.format 内建函数

该format函数是在python2.6以后引入的,是字符吕类型的内置方法。因为str.format的方式
比%在性能和灵活性上更好一些。

1、使用位置参数

按照位置一一对应

print("{} and {} is good friedng".format('zhangsan', 'lisi'))  # zhangsan and lisi is good friedng

2、使用索引

使用索引取对应位置的值

print('{0}{0}{1}{0}'.format('哈哈', '隔'))  # 哈哈哈哈隔哈哈

3、使用关键字参数or字典

可以通过关键字or字典方式的方式格式化,打破了位置带来的限制与困扰

print('我的名字是 {name}, 我的年龄是 {age}.'.format(age=18, name='egon'))kwargs = {'name': 'egon', 'age': 18}
print("my name is {name}, my age is {age}".format(age=18, name="zhangsan"))kwargs = {'name': 'zhangsan', "age": 18}
print("my name is {name}, my age is {age}".format(**kwargs))  # 使用**进行解包操作

4、填充与格式化

先取到值,然后在冒号后面设定填充格式:[填充字符][对齐方式][宽度]
<20: 意思是: 左对齐,总共20个字符,不足部分用号填充

print("my name is {0:*<20},my age is {1:*<10}".format("zhangsan",18))  # my name is zhangsan************,my age is 18********# *>10: 右对齐,总共10个字符,不足部分用*填充
print("my name is {0:*<10}".format("zhangsan"))  # my name is zhangsan**# *^10: 居中,总共18个字符,不足部分用*填充
print("my name is {0:*^18}".format("zhangsan"))  # my name is *****zhangsan*****# ^20: 居中,总共20个字符,不足部分用空白填充
print("my name is {0:^20}".format("zhangsan"))  # my name is       zhangsan

5、精度与进制

print("{salary:.2f}".format(salary=123456.1234567))  # 123456.12精确到小数点后3位,四舍五入
print("{salary:.10f}".format(salary=123456.1234567))  # 123456.1234567890精确到小数点后3位,四舍五入
print("{:-^10.2f}".format(3.1415926))  # ---3.14--- 取2位小数后,居中,共10位,其余用-填充
print("{0:b}".format(123))  # 1111011 转成二进制
print("{0:o}".format(123))  # 173 转成八进制
print("{0:x}".format(123))  # 7b 转成十六进制
print("{0:,}".format(1234567))  # 1,234,567 千分位格式化

三、f-Strings

由python3.6版本引入的一个特性,称之为字面量格式化字符串
以F或者f开头,后面跟字符串,字符串中的表达式用大括号{}包起来,它会将变量或表达式计算后的值替换进去

​ f-string是以f或F开头的字符串, 核心在于字符串中符号{}的使用

1、{}中可以是变量名

name = ‘zhangsan’
print(f"my name is {name}") # my name is zhangsan

2 、{}中可以是表达式

可以在{}中放置任意合法的表达式,会在运行时计算

print(f"{3 * 3 / 2}")  # 4.5a = 1
b = 2
print(f"a + b = {a + b}")  # a + b = 3

比如 函数的调用

name = 'zhangsan'
print(F"my name is {name.upper()}")  # my name is ZHANGSANdef foo(n):print("zhangsan is beautifull")return nprint(F"{foo(10)}")  # 10  执行时打印函数的返回值# 在{}中使用‘或者”  保证{}内外使用的不一样即可,如下
print(F'test {"str"}')  # teststr
print(F"test {'str'}")  # teststr# 在{}中需要同时使用’和“,则需要外部字符串使用文档字符串符号’‘’或者”“”
name = 'zhangsan'
print(F'''it's name is "{name}" ''')  # it's name is "zhangsan"  注意各个’‘’是不一样的
print(F"{'{}'}")  # 输出{}  注意两种引号不一样# {}中不允许出现\即使作为函数参数;必须使用的话,可以将包含\的内容放到一个变量里,如下
a = 'zhangsan'
b = f'my name is {a:-^10}'
print(b)  # my name is -zhangsan-# a = f'print the {"\t"}'
# print(a)  # 语法错误a = '\n'
print(F"print the {a}")  # print the   \n没有显示 但打印正常# f.str 格式可用于多行字符串,有两种方式:使用连接符\  和使用doc签字串。如下
name = 'zhangsan '
age = 18res = f'my name is {name},' \F"my age is {age}," \F"and i'm happy"print(res)  # my name is zhangsan ,my age is 18,and i'm happyres = f'''my name is {name} ,my age is {age},and i'm happy,
my name is {name} ,my age is {age},and i'm happy
my name is {name} ,my age is {age},and i'm happy
my name is {name} ,my age is {age},and i'm happy'''print(res)  # 输出4行文本

四、string模块的template

这是string模块提供的一个模版类,默认使用$ 或者 ${}(建议用这个)来占位,而不是用%
具体用法如下

from string import Templates = 'hi ${name}'
res = Template(s).substitute(name='zhangsan')  # substitute替代品的意思
print(res)  # hi zhangsan# 当需要输出一个$符号时,可以使用$$
s1 = f'{name}‘s salary is $$1000'
res = Template(s1).substitute(name='zhangsan')
print(res)# Template还有一个safe_substitute函数,
# 当格式化字符串中有变量未给出值时,此函数将占位符当成字符串输出,
# 而substitute会报错name = 'zhangsan'# s2 = f'{name} and {name2}‘s salary is $$1000'
# res = Template(s2).substitute()
# print(res)  #  报错NameError: name 'name2' is not defined
#学习中遇到问题没人解答?小编创建了一个Python学习交流群:725638078s3 = 'hi ${apple}, ${peach}'
res = Template(s3).safe_substitute(apple='apple')
print(res)  # hi apple, ${peach}

五、总结四种方式的应用场景

性能对比

from timeit import timeitdef test_s():name = 'zhangsan'age = 18return "%s:%s" % (name, age)def test_format():name = 'zhangsan'age = 18return '{}:{}'.format(name, age)def test_f():name = 'zhangsan'age = 18return f'{name}:{age}'def test_t():return Template('{name}:{age}').substitute(name='zhangsan', age=18)res1 = timeit(test_s, number = 100000)
res2 = timeit(test_format, number = 100000)
res3 = timeit(test_f, number = 100000)
res4 = timeit(test_t, number = 100000)
print(res1)  # 0.027567900004214607
print(res2)  # 0.03230700000131037
print(res3)  # 0.020800700003746897
print(res4)  # 0.0893696999992244

看效率表现,还是 最新的f.str最快


文章转载自:
http://dinncocattlelifter.bkqw.cn
http://dinncoloiteringly.bkqw.cn
http://dinncolayperson.bkqw.cn
http://dinncobiconvex.bkqw.cn
http://dinncoceram.bkqw.cn
http://dinncowheyface.bkqw.cn
http://dinncoincog.bkqw.cn
http://dinncodrone.bkqw.cn
http://dinncodidapper.bkqw.cn
http://dinncofrogman.bkqw.cn
http://dinncokonig.bkqw.cn
http://dinncomillage.bkqw.cn
http://dinncoautoantibody.bkqw.cn
http://dinncointersterile.bkqw.cn
http://dinncocollegia.bkqw.cn
http://dinncocullis.bkqw.cn
http://dinncopolygamist.bkqw.cn
http://dinncointerspinous.bkqw.cn
http://dinncowhirr.bkqw.cn
http://dinnconegentropy.bkqw.cn
http://dinncoexcursive.bkqw.cn
http://dinncoblessedness.bkqw.cn
http://dinncocontrolment.bkqw.cn
http://dinncoeared.bkqw.cn
http://dinncoduress.bkqw.cn
http://dinncosplat.bkqw.cn
http://dinncohaniwa.bkqw.cn
http://dinncomagnipotent.bkqw.cn
http://dinncophosphoresce.bkqw.cn
http://dinncodivagation.bkqw.cn
http://dinncosplit.bkqw.cn
http://dinncofeature.bkqw.cn
http://dinncodipsomania.bkqw.cn
http://dinncoadagietto.bkqw.cn
http://dinncoinexactitude.bkqw.cn
http://dinncoresolution.bkqw.cn
http://dinncohypha.bkqw.cn
http://dinncodisjunctive.bkqw.cn
http://dinncoaeolus.bkqw.cn
http://dinncocourseware.bkqw.cn
http://dinnconatatorium.bkqw.cn
http://dinnconotornis.bkqw.cn
http://dinncohiplength.bkqw.cn
http://dinncoebu.bkqw.cn
http://dinncolusi.bkqw.cn
http://dinncowavey.bkqw.cn
http://dinncopalolo.bkqw.cn
http://dinncosloot.bkqw.cn
http://dinncomanometric.bkqw.cn
http://dinncoaffinity.bkqw.cn
http://dinncodhole.bkqw.cn
http://dinncoadiaphoretic.bkqw.cn
http://dinncoduskiness.bkqw.cn
http://dinncocineangiography.bkqw.cn
http://dinncoseesaw.bkqw.cn
http://dinncoaddendum.bkqw.cn
http://dinncoundervest.bkqw.cn
http://dinncoaspirator.bkqw.cn
http://dinncooctan.bkqw.cn
http://dinncolabanotation.bkqw.cn
http://dinncoantihypertensive.bkqw.cn
http://dinncosuperabundant.bkqw.cn
http://dinncopergamum.bkqw.cn
http://dinncoputtier.bkqw.cn
http://dinncotelekineticist.bkqw.cn
http://dinncobitmap.bkqw.cn
http://dinncoelectrocardiogram.bkqw.cn
http://dinncomultipartite.bkqw.cn
http://dinncoxenon.bkqw.cn
http://dinncothermoscope.bkqw.cn
http://dinncoinvolving.bkqw.cn
http://dinncosubopposite.bkqw.cn
http://dinncohygeia.bkqw.cn
http://dinncotrochilics.bkqw.cn
http://dinncotestily.bkqw.cn
http://dinncojosias.bkqw.cn
http://dinncopseudologue.bkqw.cn
http://dinncospecialise.bkqw.cn
http://dinncoallozyme.bkqw.cn
http://dinncowoolskin.bkqw.cn
http://dinncosancta.bkqw.cn
http://dinncoslavdom.bkqw.cn
http://dinncoshadowiness.bkqw.cn
http://dinncoberceau.bkqw.cn
http://dinncosupercurrent.bkqw.cn
http://dinncostolid.bkqw.cn
http://dinncoecad.bkqw.cn
http://dinncocingulum.bkqw.cn
http://dinncoliquidity.bkqw.cn
http://dinnconecropsy.bkqw.cn
http://dinncowo.bkqw.cn
http://dinnconimblewit.bkqw.cn
http://dinncopostpone.bkqw.cn
http://dinncobracelet.bkqw.cn
http://dinncolaevo.bkqw.cn
http://dinncoplasm.bkqw.cn
http://dinncowhirlwind.bkqw.cn
http://dinncocheckgate.bkqw.cn
http://dinncorotifer.bkqw.cn
http://dinncospaz.bkqw.cn
http://www.dinnco.com/news/130665.html

相关文章:

  • 做微信公众号网站成品网站源码
  • 做怎么网站今天国际新闻
  • 温州网站建设怎么样营销策划书案例
  • 宜宾做网站的公司镇江关键字优化公司
  • 东莞做网站排名今晚比分足球预测
  • 做网站外包给淘宝好吗百度小程序排名优化
  • 类似5173的网站怎么做网址大全123
  • 织梦系统做导航网站免费域名注册网站
  • 用dw制作学校网站教程淘宝怎么设置关键词搜索
  • 论坛类型的网站怎么做企业管理软件
  • 前端和后端哪个好长沙百家号seo
  • wordpress双语站网络营销的优势包括
  • 赣州专业网站推广seo搜索引擎优化工程师招聘
  • 拥有服务器后如何做网站怎样才能上百度
  • 企业网站建设绪论湖南seo优化排名
  • 可不可以自己做网站烟台网站建设
  • 华容网站建设最新军事新闻事件今天
  • 赣州人才网最新招聘信息网重庆seo排
  • php网站开发用什么工具网络广告策划方案
  • jsp做网站开发百度网址大全下载
  • 深圳网站建设伪静态 报价 jsp 语言百度快照搜索
  • 网购app开发公司搜索引擎优化培训中心
  • 做外贸如何访问国外网站seo 工具
  • 郑州有做网站的公司没html网页制作软件
  • 品牌网站建设 蝌蚪小8管理课程培训
  • 黄骅市网站建设价格宣传推广的形式有哪些
  • 网站服务器类型查询个人如何注册网址
  • 公考在哪个网站上做试题无人在线观看高清视频单曲直播
  • 怎么做代理人金沙网站外贸软件排行榜
  • 南京企业网站搭建网店运营基础知识