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

相关推荐
@forever@2 小时前
【JAVA】LinkedList与链表
java·python·链表
程序员爱钓鱼2 小时前
Python编程实战:面向对象与进阶语法——类型注解与代码规范(PEP 8)
后端·python·ipython
程序员爱钓鱼2 小时前
Python实战:用高德地图API批量获取地址所属街道并写回Excel
后端·python·ipython
reasonsummer3 小时前
【教学类-97-06】20251105“葡萄”橡皮泥黏贴(小班主题《苹果与橘子》)
python
卖个几把萌4 小时前
【16】Selenium+Python 接管已打开谷歌浏览器
python·selenium·测试工具
像风一样的男人@4 小时前
python --两个文件夹文件名比对(yolo 图和label标注比对检查)
windows·python·yolo
lllsure4 小时前
【Python】Dict(字典)
开发语言·python
tianyuanwo5 小时前
Rust开发完全指南:从入门到与Python高效融合
开发语言·python·rust
如何原谅奋力过但无声6 小时前
TensorFlow 2.x常用函数总结(持续更新)
人工智能·python·tensorflow
程序员-小李6 小时前
基于 Python + OpenCV 的人脸识别系统开发实战
开发语言·python·opencv