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

相关推荐
郭庆汝4 小时前
pytorch、torchvision与python版本对应关系
人工智能·pytorch·python
思则变7 小时前
[Pytest] [Part 2]增加 log功能
开发语言·python·pytest
漫谈网络8 小时前
WebSocket 在前后端的完整使用流程
javascript·python·websocket
try2find9 小时前
安装llama-cpp-python踩坑记
开发语言·python·llama
博观而约取10 小时前
Django ORM 1. 创建模型(Model)
数据库·python·django
精灵vector12 小时前
构建专家级SQL Agent交互
python·aigc·ai编程
Zonda要好好学习12 小时前
Python入门Day2
开发语言·python
Vertira12 小时前
pdf 合并 python实现(已解决)
前端·python·pdf
太凉12 小时前
Python之 sorted() 函数的基本语法
python
项目題供诗12 小时前
黑马python(二十四)
开发语言·python