0
def myfunc (*args, **kwargs):
    print (args)
    print (kwargs)
    print (f'I would like {args[0]} {kwargs['food']}')
    #Example #2 print ('I would like {} {}'.format(args[0], kwargs['food']))

myfunc(10,20,30,fruit = 'orange', food = 'eggs', animal = 'dog')

When I execute the code above, I get an error that says:

SyntaxError: f-string: unmatched '['

However, when I execute "Example #2" instead, I get the correct output:

I would like 10 eggs

What is wrong with my syntax when using f-string literal?

2 Answers2

3

Don't use the same quotes surrounding the string in the string itself. You are terminating the string early.

Use "food" not 'food' or use triple single- or double-quotes like:

print (f'''I would like {args[0]} {kwargs['food']}''')
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
  • Expanding a little on this answer: you can also use double quotes on the outer f-string `f"I would like {args[0]} {kwargs['food']}"` – Marcel Wilson Dec 15 '22 at 22:20
0

When you use single quote inside of an f-string you need to wrap it in double quotes. in your Example, you will need to replace as follows.

print (f'I would like {args[0]} {kwargs['food']}')

#replace with

print (f"I would like {args[0]} {kwargs['food']}")
David Buck
  • 3,752
  • 35
  • 31
  • 35