You have no variables in your string literal, you didn't escape the {
and }
, and you broke the indentation. Try this:
def stripMargin(txt):
return '\n'.join([r.split('|', 1)[1] for r in txt.split('\n')])
def funky(data1,data2):
return stripMargin("""|{{
|.data1="{0}",
|.data2="{1}",
|}},""".format(data1,data2))
print(funky("egg", "dog"))
The |
-part combined with stripMargin
ensures that the indentation of the generated code (the object language) does not interfere with the indentation of python (the metalanguage).
I would actually indent the generated code differently:
def funky(data1,data2):
return stripMargin("""|{{
| .data1="{0}",
| .data2="{1}",
|}},""".format(data1,data2))
Since you don't need any common indentation in the final output, you can also use dedent
:
from textwrap import dedent
def funky2(data1,data2):
return dedent("""\
{{
.data1="{0}",
.data2="{1}",
}},""").format(data1,data2)
(Thanks @user2357112 for pointing it out)