在字符串中嵌入表达式的 Python 等价物是什么?(即 Ruby 中的“#{expr}”)

hop*_*pia 4 ruby python language-comparisons string-interpolation

在 Python 中,我想创建一个带有嵌入式表达式的字符串块。
在 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
Run Code Online (Sandbox Code Playgroud)

jfs*_*jfs 5

更新: 从 Python 3.6 开始,有格式化的字符串文字(f-strings)可以实现文字字符串插值:f"..{get_val()+1}..."


如果您需要的不仅仅是由str.format()and提供的简单字符串格式,%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))
Run Code Online (Sandbox Code Playgroud)

输出

This is a sample string
that references a function whose value is: 100
Incrementing the value: 101
Run Code Online (Sandbox Code Playgroud)

使用 @stringfunction 进行 Python 模板化