Search code examples
pythonmaya

KeyError when using .format to structure an expression


I am using .format to edit and add an expression to an attribute. I will get a KeyError when trying to execute the code:

modi_expr = """
    if (frame < 6) {
        {0}.frameExtension=6;
    }
    else if (frame > 73) {
        {0}.frameExtension=73;
    }
    else{
        {0}.frameExtension=frame;
    }
""".format('planeShape2')

Whereas if I used % as follows, while it works, it requires me to write 3 times of the same variable.

expr_to_use = """
    if (frame < 6) {
        %s.frameExtension=6;
    }
    else if (frame > 73) {
        %s.frameExtension=73;
    }
    else{
        %s.frameExtension=frame;
    }
""" % ('planeShape2', 'planeShape2', 'planeShape2')

If using % is the way to go, is there a way that I can write it once? If not, are there a better alternative way of approaching this?


Solution

  • Use {{ and }} to escape the non-formatting braces.

    From the docs: https://docs.python.org/3/library/string.html#format-string-syntax

    If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }}.

    modi_expr = """
        if (frame < 6) {{
            {0}.frameExtension=6;
        }}
        else if (frame > 73) {{
            {0}.frameExtension=73;
        }}
        else{{
            {0}.frameExtension=frame;
        }}
    """.format('planeShape2')
    
    print(modi_expr)
    

    Or you can also use f-strings for python >= 3.6

    var = 'planeShape2'
    
    modi_expr = f"""
        if (frame < 6) {{
            {var}.frameExtension=6;
        }}
        else if (frame > 73) {{
            {var}.frameExtension=73;
        }}
        else{{
            {var}.frameExtension=frame;
        }}
    """
    

    The output will be

     if (frame < 6) {
            planeShape2.frameExtension=6;
        }
        else if (frame > 73) {
            planeShape2.frameExtension=73;
        }
        else{
            planeShape2.frameExtension=frame;
        }