python字符串格式化方式解析

yipeiwu_com5年前Python基础

1.%格式符

name = '李四'
age = 18
a = "姓名:%s,年龄:%s"%(name,age)
print(a)   #姓名:李四,年龄:18
​
b = "%(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 + b
a = 1
b = 2
print('求和的结果为' + f'{sum_a_b(a,b)}')

#多行f 反斜杠
name = 'barry'
age = 18
ajd = '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 = 5
print(f'{(lambda x: x*2) (x)}') # 10

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Pycharm中出现ImportError:DLL load failed:找不到指定模块的解决方法

Pycharm中出现ImportError:DLL load failed:找不到指定模块的解决方法

关于conda安装matplotlib报错 最近在师姐机器上跑实验的时候,想利用matplotlib包来绘制损失曲线图,安装过程中碰到了一些小麻烦,感觉之前好像也碰到过类似的问题,网上一...

Tensorflow 合并通道及加载子模型的方法

Tensorflow 合并通道及加载子模型的方法

最近在使用Tensorflow 实现DNN网络时,遇到一些问题。目前网上关于Tensorflow的资料还比较少,现把问题和解决方法写出来,仅供参考。 (1)将两个子模型的输出合并到一个通...

Python脚本判断 Linux 是否运行在虚拟机上

在 WebHostingTalk 论坛上有些国外奸商会把虚拟机当作独立服务器卖,去年7月份的时候就有一位中国同胞上当受骗,并在 WHT 上发帖声讨,证据确凿,甚至连服务商自己也承认,回帖...

python网络编程之文件下载实例分析

本文实例讲述了python网络编程之文件下载实现方法。分享给大家供大家参考。具体如下: 真是越看越喜欢python啊,想要了解它提供的http和ftp下载功能,原来是如此的简单。 1、相...

Windows上使用virtualenv搭建Python+Flask开发环境

关于virtualenv: VirtualEnv用于在一台机器上创建多个独立的Python虚拟运行环境,多个Python环境相互独立,互不影响,它能够: 1.在没有权限的情况下安装新套件...