python字符串格式化方式解析
Python  /  管理员 发布于 7年前   155
1.%格式符
name = '李四'age = 18a = "姓名:%s,年龄:%s"%(name,age)print(a) #姓名:李四,年龄:18b = "%(name)s,%(age)s"%{'name':'张三','age':18}print(b) #张三,18
这种格式化并不是很好,因为它很冗长并且容易导致错误,比如没有正确显示元组或字典
2.str.format()
name = '李四'age = 18# 替换字段用大括号进行标记a1 = "hello, {}. you are {}?".format(name,age)print(a1) #hello, 李四. you are 18?# 通过索引来以其他顺序引用变量a2 = "hello, {1}. you are {0}?".format(age,name)print(a2) #hello, 李四. you are 18?# 通过参数来以其他顺序引用变量a3 = "hello, {name}. you are {age1}?".format(age1=age,name=name)print(a3) #hello, 李四. you are 18?# 从字典中读取数据时还可以使用 **data = {"name":"张三","age":18}a4 = "hello, {name}. you are {age}?".format(**data)print(a4) #hello, 李四. you are 18?
在处理多个参数和更长的字符串时仍然可能非常冗长
3.f-Strings
f-strings 是指以 f 或 F 开头的字符串,其中以 {} 包含的表达式会进行值替换。
name = '李四'age = 18# F 和 f 的简单使用b1 = f"hello, {name}. you are {age}?"b2 = F"hello, {name}. you are {age}?"print(b1) # hello, 李四. you are 18?print(b2) # hello, 李四. you are 18?# 字典也可以teacher = {'name': 'meet', 'age': 18}msg = f"The teacher is {teacher['name']}, aged {teacher['age']}"print(msg) # The comedian is meet, aged 18# 列表也行l1 = ['meet', 18]msg = f'姓名:{l1[0]},年龄:{l1[1]}.'print(msg) # 姓名:meet,年龄:18.#可以插入表达式def sum_a_b(a,b): return a + ba = 1b = 2print('求和的结果为' + f'{sum_a_b(a,b)}')#多行f 反斜杠name = 'barry'age = 18ajd = 'handsome'speaker = f'Hi {name}.'\ f'You are {age} years old.'\ f'You are a {ajd} guy!'print(speaker) #Hi barry.You are 18 years old.You are a handsome guy!print(f"{You are very \"handsome\"}") #报错#括号的处理 -->重点:两对为一组print(f"{{73}}") # {73}print(f"{{{73}}}") # {73}print(f"{{{{73}}}}") # {{73}}m = 21# ! , : { } ;这些标点不能出现在{} 这里面。# print(f'{;12}') # 报错# 所以使用lambda 表达式会出现一些问题。# 解决方式:可将lambda嵌套在圆括号里面解决此问题。x = 5print(f'{(lambda x: x*2) (x)}') # 10
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号