-1

I was writing a little code, that I left below:

"""
    for(i=0;i<{0};i++){
    eventObj
    }
    """.format('5')

it shows the next error:

KeyError: '\n    eventObj\n    '

but if I write:

"""
    for(i=0;i<%s;i++){
    eventObj
    }
    """ % ('5')

it doesn't show error and works without any kind of problem, I thought that both are equivalent

The question is: why happen that?

Sho_Lee
  • 149
  • 4
  • 1
    You string has other `{` `}` in it. Format uses those as markers but `%` does not. So the other `{` `}` cause an error in format. – khelwood May 15 '20 at 23:34

1 Answers1

1

When you use the format() method, anything between { and } is treated as a parameter name or number that should be replaced with the corresponding argument.

Your string contains

{
    eventObj
    }

You get an error because there's no parameter that matches that name.

If you want to have literal { characters in a format string, you have to double them.

"""
    for(i=0;i<{0};i++){{
    eventObj
    }}
    """.format('5')

See How can I print literal curly-brace characters in python string and also use .format on it?

You don't get an error when you use % because it uses format operators beginning with %; { has no special meaning in the format string. In that case, you need to double the % character if it should be literal, but you don't have any literal % in your example.

Barmar
  • 741,623
  • 53
  • 500
  • 612