在 Python 中,我想创建一个带有嵌入式表达式的字符串 block 。
在 Ruby 中,代码如下所示:
def get_val
100
end
def testcode
s=<<EOS
This is a sample string that references a variable whose value is: #{get_val}
Incrementing the value: #{get_val + 1}
EOS
puts s
end
testcode
最佳答案
更新:自 Python 3.6 以来,有 formatted string literals (f-strings)启用文字字符串插值:f"..{get_val()+1}..."
如果您需要的不仅仅是 str.format()
提供的简单字符串格式和 %
然后 templet
模块可用于插入 Python 表达式:
from templet import stringfunction
def get_val():
return 100
@stringfunction
def testcode(get_val):
"""
This is a sample string
that references a function whose value is: ${ get_val() }
Incrementing the value: ${ get_val() + 1 }
"""
print(testcode(get_val))
输出
This is a sample string
that references a function whose value is: 100
Incrementing the value: 101
关于python - 在 Python 中将表达式嵌入字符串的等价物是什么? (即 Ruby 中的 "#{expr}"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9763069/