2024-04-20 06:46:49 发布
网友
Ruby示例:
name = "Spongebob Squarepants" puts "Who lives in a Pineapple under the sea? \n#{name}."
成功的Python字符串连接对我来说似乎很冗长。
由于Python2.6.X,您可能需要使用:
"my {0} string: {1}".format("cool", "Hello there!")
我开发了interpy包,它可以在Python中实现字符串插值。
只需通过pip install interpy安装即可。 然后,在文件的开头添加一行# coding: interpy!
pip install interpy
# coding: interpy
示例:
#!/usr/bin/env python # coding: interpy name = "Spongebob Squarepants" print "Who lives in a Pineapple under the sea? \n#{name}."
Python 3.6将添加类似于Ruby字符串插值的literal string interpolation。从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中的%运算符可用于string interpolation。第一个操作数是要插值的字符串,第二个操作数可以有不同的类型,包括“映射”,将字段名映射到要插值的值。在这里,我使用局部变量字典locals()将字段名name映射为它作为局部变量的值。
%
locals()
name
使用最新Python版本的.format()方法的相同代码如下所示:
.format()
name = "Spongebob Squarepants" print("Who lives in a Pineapple under the sea? {name!s}.".format(**locals()))
还有^{}类:
tmpl = string.Template("Who lives in a Pineapple under the sea? $name.") print(tmpl.substitute(name="Spongebob Squarepants"))
由于Python2.6.X,您可能需要使用:
我开发了interpy包,它可以在Python中实现字符串插值。
只需通过
pip install interpy
安装即可。 然后,在文件的开头添加一行# coding: interpy
!示例:
Python 3.6将添加类似于Ruby字符串插值的literal string interpolation。从Python的那个版本(计划在2016年底发布)开始,您将能够在“f-strings”中包含表达式,例如
在3.6之前,最接近的是
Python中的
%
运算符可用于string interpolation。第一个操作数是要插值的字符串,第二个操作数可以有不同的类型,包括“映射”,将字段名映射到要插值的值。在这里,我使用局部变量字典locals()
将字段名name
映射为它作为局部变量的值。使用最新Python版本的
.format()
方法的相同代码如下所示:还有^{} 类:
相关问题 更多 >
编程相关推荐