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

相关推荐
START_GAME7 分钟前
深度学习Diffusers:用 DiffusionPipeline 实现图像生成
开发语言·python·深度学习
Deamon Tree38 分钟前
后端开发常用Linux命令
linux·运维·python
卡卡恩2 小时前
使用uv创建系统全局python执行环境
python
查士丁尼·绵2 小时前
笔试-座位调整
python
飞翔的佩奇3 小时前
【完整源码+数据集+部署教程】【运动的&足球】足球场地区域图像分割系统源码&数据集全套:改进yolo11-RFAConv
前端·python·yolo·计算机视觉·数据集·yolo11·足球场地区域图像分割系统
MYX_3094 小时前
第四章 多层感知机
开发语言·python
盼哥PyAI实验室4 小时前
《Python爬虫 + 飞书自动化上传》全流程详细讲解
爬虫·python·飞书
时空无限5 小时前
conda 管理 python 版本和虚拟环境
python·conda
隔壁程序员老王5 小时前
基于 Python 的坦克大战小程序,使用 Pygame 库开发
python·小程序·pygame·1024程序员节
kaikaile19955 小时前
Java面试题总结
开发语言·python