Python 中是否有与 Ruby 字符串插值等效的函数?[重复]
- 2025-01-03 08:40:00
- admin 原创
- 90
问题描述:
Ruby 示例:
name = "Spongebob Squarepants"
puts "Who lives in a Pineapple under the sea?
#{name}."
成功的 Python 字符串连接对我来说似乎很冗长。
解决方案 1:
Python 3.6 将添加类似于 Ruby 字符串插值的文字字符串插值。从该版本的 Python(计划于 2016 年底发布)开始,您将能够在“f 字符串”中包含表达式,例如
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
作为局部变量映射到其值。
使用最新 Python 版本的方法的相同代码.format()
如下所示:
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"))
解决方案 2:
从 Python 2.6.X 开始你可能需要使用:
"my {0} string: {1}".format("cool", "Hello there!")
解决方案 3:
我开发了interpy包,它可以在 Python 中实现字符串插值。
只需通过 安装它pip install interpy
。然后# coding: interpy
在文件开头添加该行!
例子:
#!/usr/bin/env python
# coding: interpy
name = "Spongebob Squarepants"
print "Who lives in a Pineapple under the sea?
#{name}."
解决方案 4:
Python 的字符串插值类似于 C 的 printf()
如果你尝试:
name = "SpongeBob Squarepants"
print "Who lives in a Pineapple under the sea? %s" % name
标签%s
将被变量替换name
。您应该查看打印函数标签:http ://docs.python.org/library/functions.html
解决方案 5:
根据 PEP 498 中的规定,字符串插值将包含在 Python 3.6 中。您将能够执行以下操作:
name = 'Spongebob Squarepants'
print(f'Who lives in a Pineapple under the sea?
{name}')
请注意,我讨厌海绵宝宝,因此写这篇文章有点痛苦。:)
解决方案 6:
您还可以拥有
name = "Spongebob Squarepants"
print "Who lives in a Pineapple under the sea?
{name}.".format(name=name)
http://docs.python.org/2/library/string.html#formatstrings
解决方案 7:
import inspect
def s(template, **kwargs):
"Usage: s(string, **locals())"
if not kwargs:
frame = inspect.currentframe()
try:
kwargs = frame.f_back.f_locals
finally:
del frame
if not kwargs:
kwargs = globals()
return template.format(**kwargs)
用法:
a = 123
s('{a}', locals()) # print '123'
s('{a}') # it is equal to the above statement: print '123'
s('{b}') # raise an KeyError: b variable not found
PS:性能可能是一个问题。这对本地脚本有用,但对生产日志没有用。
重复:
Python 字符串格式化:% 与 .format
在 Python 中,将表达式嵌入字符串的等价内容是什么?(例如 Ruby 中的“#{expr}”)
Ruby 中与 Python 中的
s= "hello, %s. Where is %s?" % ("John","Mary")
等价的是什么Python 中是否有与 Ruby 的字符串插值等效的函数?
解决方案 8:
Python 3.6 及更新版本使用 f 字符串进行文字字符串插值:
name='world'
print(f"Hello {name}!")
解决方案 9:
对于旧版 Python(在 2.4 上测试),上面的解决方案指明了方向。您可以这样做:
import string
def try_interp():
d = 1
f = 1.1
s = "s"
print string.Template("d: $d f: $f s: $s").substitute(**locals())
try_interp()
你会得到
d: 1 f: 1.1 s: s