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

标签 python ruby language-comparisons string-interpolation

在 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 Templating with @stringfunction .

关于python - 在 Python 中将表达式嵌入字符串的等价物是什么? (即 Ruby 中的 "#{expr}"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9763069/

相关文章:

python - 为什么我可以从终端运行此命令,但当我的 python 从终端为我运行它时却收到错误?

python - Pandas - 汇总行以填充缺失数据

ruby-on-rails - 将一个 Controller 重定向到另一个 Controller

haskell - Haskell 是 Lisp 语言吗?

python - 从 Ruby 移植到 Python : What to do with 'yield'

python - python中的全局变量引用

python - 为什么需要 Homebrew 在 MacOS 上安装 WeasyPrint?可以用Anaconda代替吗?

ruby - 在 Ruby 中,将 "chomp"放在字符串开头而不是结尾的最简单方法是什么?

ruby - 与 ruby​​ `Marshal` 概念混淆

haskell - Clojure STM 与 Haskell STM 有何不同?