Python 是否有像 Ruby 那样的字符串插值?
Python 提供与 Ruby 相当的字符串插值吗?
在 Ruby 中,字符串插值允许将表达式插入到字符串中,从而增强代码可读性。 Ruby 字符串插值的示例:
name = "Spongebob Squarepants" puts "Who lives in a Pineapple under the sea? \n#{name}."
对于 Python 开发人员来说,等效的字符串连接可能看起来很冗长。
Python 3.6 及更高版本中的 Python 字符串插值
值得庆幸的是,Python 3.6 引入了与 Ruby 类似的文字字符串插值。在 Python 3.6 中,“f-strings”允许包含表达式:
name = "Spongebob Squarepants" print(f"Who lives in a Pineapple under the sea? {name}.")
Python 3.6 之前的替代方案
在 Python 3.6 之前,请考虑以下选项:
- % 运算符: 使用用于字符串插值的 % 运算符。第一个操作数是要插值的字符串,第二个操作数可以包含将字段名称映射到值的“映射”。可以使用 locals() 创建映射。
name = "Spongebob Squarepants" print("Who lives in a Pineapple under the sea? %(name)s." % locals())
- .format() 方法: 利用 .format() 方法插入字符串:
name = "Spongebob Squarepants" print("Who lives in a Pineapple under the sea? {name!s}.".format(**locals()))
- string.Template类: 使用 string.Template 类进行字符串插值:
tmpl = string.Template("Who lives in a Pineapple under the sea? $name.") print(tmpl.substitute(name="Spongebob Squarepants"))
以上是Python 是否有像 Ruby 那样的字符串插值?的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

使用FiddlerEverywhere进行中间人读取时如何避免被检测到当你使用FiddlerEverywhere...

如何在10小时内教计算机小白编程基础?如果你只有10个小时来教计算机小白一些编程知识,你会选择教些什么�...

攻克Investing.com的反爬虫策略许多人尝试爬取Investing.com(https://cn.investing.com/news/latest-news)的新闻数据时,常常�...

Python3.6环境下加载pickle文件报错:ModuleNotFoundError:Nomodulenamed...

使用Scapy爬虫时管道文件无法写入的原因探讨在学习和使用Scapy爬虫进行数据持久化存储时,可能会遇到管道文�...
