In Python, I’d like to create a string block with embedded expressions.
In Ruby, the code looks like this:
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
Update: since Python 3.6, there are formatted string literals (f-strings) which enable a literal string interpolation:
f"..{get_val()+1}..."If you need more than just a simple string formatting provided by
str.format()and%thentempletmodule could be used to insert Python expressions:Output
Python Templating with @stringfunction.