Ruby的例子:
name = "Spongebob Squarepants"
puts "Who lives in a Pineapple under the sea? \n#{name}."
成功的Python字符串连接对我来说似乎很冗长。
Ruby的例子:
name = "Spongebob Squarepants"
puts "Who lives in a Pineapple under the sea? \n#{name}."
成功的Python字符串连接对我来说似乎很冗长。
当前回答
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字符串格式:% vs. .format Python中与在字符串中嵌入表达式相当的是什么?(即。“#{expr}” Ruby与Python的s= "hello, %s. "对应的是什么?%s在哪里?”%(“约翰”,“玛丽”) Python中是否有类似于Ruby的字符串插值函数?
其他回答
按照PEP 498的规定,Python 3.6将包含字符串插值。你可以这样做:
name = 'Spongebob Squarepants'
print(f'Who lives in a Pineapple under the sea? \n{name}')
请注意,我讨厌海绵宝宝,所以写这篇文章有点痛苦。:)
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
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字符串格式:% vs. .format Python中与在字符串中嵌入表达式相当的是什么?(即。“#{expr}” Ruby与Python的s= "hello, %s. "对应的是什么?%s在哪里?”%(“约翰”,“玛丽”) Python中是否有类似于Ruby的字符串插值函数?
从Python 2.6开始。X你可能想用:
"my {0} string: {1}".format("cool", "Hello there!")
我开发了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? \n#{name}."