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

相关推荐
多多*14 分钟前
微服务网关SpringCloudGateway+SaToken鉴权
linux·开发语言·redis·python·sql·log4j·bootstrap
梓仁沐白14 分钟前
【Kotlin】协程
开发语言·python·kotlin
Java Fans31 分钟前
在WPF项目中集成Python:Python.NET深度实战指南
python·.net·wpf
豌豆花下猫1 小时前
Python 潮流周刊#105:Dify突破10万星、2025全栈开发的最佳实践
后端·python·ai
嘻嘻哈哈OK啦1 小时前
day46打卡
python
木头左1 小时前
Docker容器化技术概述与实践
python
坚持就完事了1 小时前
大二下期末
python·numpy·pandas
蹦蹦跳跳真可爱5892 小时前
Python----目标检测(使用YOLO 模型进行线程安全推理和流媒体源)
人工智能·python·yolo·目标检测·目标跟踪
爱补鱼的猫猫2 小时前
Pytorch知识点2
人工智能·pytorch·python
deephub2 小时前
提升模型泛化能力:PyTorch的L1、L2、ElasticNet正则化技术深度解析与代码实现
人工智能·pytorch·python·深度学习·机器学习·正则化