是否有一个与Ruby的字符串插值等效的Python?

发布于 2021-02-02 23:13:20

Ruby示例:

name = "Spongebob Squarepants"
puts "Who lives in a Pineapple under the sea? \n#{name}."

对我来说,成功的Python字符串连接似乎很冗长

关注者
0
被浏览
103
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    Python 3.6将添加与Ruby的字符串插值类似的文字字符串插值。从该版本的Python(计划于2016年底发布)开始,你将能够在“ f-strings”中包含表达式,例如

    name = "Spongebob Squarepants"
    print(f"Who lives in a Pineapple under the sea? {name}.")
    
    

    在3.6之前的版本中,最接近的是

    name = "Spongebob Squarepants"
    print("Who lives in a Pineapple under the sea? %(name)s." % locals())
    

    该%运算符可用于Python中的字符串插值。第一个操作数是要内插的字符串,第二个操作数可以具有不同的类型,包括“映射”,将字段名称映射到要内插的值。在这里,我使用了局部变量字典locals()将字段名称映射name为它的值作为局部变量。

    使用.format()最新Python版本的方法的相同代码如下所示:

    name = "Spongebob Squarepants"
    print("Who lives in a Pineapple under the sea? {name!s}.".format(**locals()))
    

    还有一个string.Template类:

    tmpl = string.Template("Who lives in a Pineapple under the sea? $name.")
    print(tmpl.substitute(name="Spongebob Squarepants"))
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看