python中三种常用格式化字符串的方法(%s, format,f-string)

前言

python中对字符串格式化是最常见的操作,对字符串格式化一般有三种方法,即%s,format和f-string。因人而异,每个人使用的格式化方法不同,为了在不同场景更高效的使用格式化方法,以及阅读别人的代码,通常三种格式化方法都要学会,不过这个知识点比较简单,容易学。

一 %s格式化字符串

%s是python在2.x版本用来格式化字符串的方法,不过到现在也还兼容。具体使用细节如下。

  • %s格式化字符串语法

%s 在字符串内作为占位符,然后通过传参格式化字符串

python 复制代码
print("my name is %s,from %s" % (name, city))
  • %s格式化示例
    位置传参格式化
python 复制代码
name = "zhangsan"
city = "shenzheng"
print("my name is %s,from %s" % (name, city))
python 复制代码
>>>
my name is zhangsan,from shenzheng

当然也可以用变量传参格式化

python 复制代码
name = "zhangsan"
city = "shenzheng"
#位置传参格式化
print("my name is %s,from %s" % (name, city))
#变量传参格式化
print("my name is %(name)s,from %(city)s" % {"city": "shenzheng", "name": "zhangsan"})
python 复制代码
>>>
my name is zhangsan,from shenzheng
my name is zhangsan,from shenzheng

二 format格式化字符串

在python 3.0 版本中python 引入了format来规范格式化字符串,用一对花括号{}替代%s作为占位符,如下。

  • format格式化字符串语法

使用{}在字符串内作为占位符,通过调用format方法格式化

python 复制代码
 print("my name is {},from {}".format(name, city))
  • format格式化示例
    format同样支持位置参数格式化和变量格式化
python 复制代码
name = "zhangsan"
city = "shenzheng"
#位置传参
print("my name is {},from {}".format(name, city))
#变量传参
print("my name is {city},from {name}".format(name=name, city=city))
python 复制代码
>>>
my name is zhangsan,from shenzheng
my name is shenzheng,from zhangsan

三 f-string格式化字符串

在python 3.6版本中引入了f-string 来格式化字符串。相比%s, formatf-string更加简洁优雅,效率和功能也更高更强,具体如下。

  • f-string格式化字符串语法

需要在字符串前面加一个f,用{}作为位置占位符

python 复制代码
print(f"my name is {name},from {city}")
  • f-string格式化字符串示例
python 复制代码
#变量格式化
print(f"my name is {name},from {city}")
python 复制代码
>>>
my name is zhangsan,from shenzheng
  • f-string计算表达式和函数调用
    f-string可以直接计算表达式和调用函数,这个功能真的很nice。
python 复制代码
import time
#f-string直接计算表达式,调用函数
def getTime():
    #获取当前时间
    time = datetime.datetime.today()
    return time
#直接调用函数
print(f"当前时间为: {getTime()}")
#计算表达式
print(f"九乘九:9 * 9 = {9*9}")
python 复制代码
当前时间为: 2024-01-21 18:28:45.848078
九乘九:9 * 9 = 81

四 总结

python格式化字符串常见的就是上面的三种,其中f-string 相比于%s,format来说更加简洁优雅,功能也更强。虽然出了f-string , 但是python现在的版本也还都支持%s和format,具体使用哪种因人而异,不过我更推荐f-string

相关推荐
一晌小贪欢1 天前
【Python数据分析】数据分析与可视化
开发语言·python·数据分析·数据可视化·数据清洗
dreams_dream1 天前
Flask
后端·python·flask
mywpython1 天前
用Python和Websockets库构建一个高性能、低延迟的实时消息推送服务
python·websocket
ZPC82101 天前
FPGA 部署ONNX
人工智能·python·算法·机器人
一晌小贪欢1 天前
Python键盘鼠标自动化库详解:从入门到精通
python·自动化·计算机外设·python鼠标·python键盘·python操控鼠标·python操控键盘
穿西装的水獭1 天前
python将Excel数据写进图片中
开发语言·python·excel
xiaoxiongip6661 天前
假设两个设备在不同网段,网关怎么设置才能通呢
网络·爬虫·python·https·智能路由器
逻极1 天前
Scikit-learn 实战:15 分钟构建生产级中国房价预测模型
python·机器学习·scikit-learn
行板Andante1 天前
AttributeError: ‘super‘ object has no attribute ‘sklearn_tags‘解决
人工智能·python·sklearn
tryCbest1 天前
Python基础之爬虫技术(一)
开发语言·爬虫·python