1

I am using python for C code generation, I want to have a function that prints the following:

{
.data1="egg",
.data2="dog",
},

I tried this function:

def funky(data1,data2):
    return """\
    {
    .data1="egg",
    .data2="dog",
    },""".format(data1,data2)

Calling "funky("egg","dog")" results in a KeyError. Relating to the unpaired curly braces.

How can I print these braces?

Hefaestion
  • 203
  • 1
  • 8

2 Answers2

3

You would need to:

  1. Use two {s and two }s.
  2. Escape the double quotes inside the string.
  3. Use {0} and {1} instead of {egg} and {dog}.

def funky(data1,data2):
    return """\
    {{
    .data1=\"{0}\",
    .data2=\"{1}\",
    }},""".format(data1,data2)
R Sahu
  • 204,454
  • 14
  • 159
  • 270
0

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)

Andrey Tyukin
  • 43,673
  • 4
  • 57
  • 93