-1

I'm using Python 3.6. I feel the below code is acting bit weird when f-strings and print statement are used together in Python

person = {"name": "Jenne", "age": 23}
print(f"Person name is {person["name"]} and age is {person["age"]}")

The above statement results in Error

But when double quotes are replaced with single quotes in the print statement across name and age then it works like a charm.

print(f"Person name is {person['name']} and age is {person['age']}")

Can anyone please explain for this behavior?

Adam Smith
  • 52,157
  • 12
  • 73
  • 112
  • 1
    That's because using the same quotes for both the string and the dictionary key will conflict. Use different quotes fixes the issue. Either way single quote for the string and double quote for key or vice-versa. – AChampion Aug 15 '17 at 19:55
  • Yes because when you have `"` it counts that as ending the string, so you get `Person name is {person[` as a string, then `name`. As opposed to `'` which makes it reference the dictionary – Professor_Joykill Aug 15 '17 at 19:55
  • 1
    @JonClements you can't escape quotes inside a f-string expression, `'\'` is not permitted – AChampion Aug 15 '17 at 19:57
  • 1
    @AChampion oh... will have to read up on that... I've never used them, but sounds like I've made a false assumption :) – Jon Clements Aug 15 '17 at 19:58
  • 1
    @JonClements Oh I didn't know that either. Thanks AChampion! – Adam Smith Aug 15 '17 at 19:58
  • 1
    @AChampion ahh huh... https://www.python.org/dev/peps/pep-0498/#id27 makes it all clear - thanks. – Jon Clements Aug 15 '17 at 20:05

1 Answers1

2

The double-quoted "name" conflicts with the double-quoted outer string f"Person name is {..." Which is to say that the first double-quote of "name" ends the previous string. You can't nest strings this way.

N.B. that f'Person name is...' or f'''Person name is...''' or f"""Person name is...""" would all work with double quotes.

Adam Smith
  • 52,157
  • 12
  • 73
  • 112
  • If this is difficult to understand, just look at the syntax highlighting of your question. It parses it the same way. – Adam Smith Aug 15 '17 at 19:56
  • Thank you Adam. Your answer is very clear. – Roopashankar Aug 15 '17 at 19:59
  • 2
    @Professor_Joykill as I pointed out you can't use `'\'` in a f-string expression - so you can't escape in this context. – AChampion Aug 15 '17 at 20:00
  • This is not a duplicate question. – Roopashankar Aug 15 '17 at 20:07
  • @AChampion and thanks for that clarification! f-strings are by a large margin my favorite new python feature in a good while. Due in large part to my use case for Python -- I write a lot of scripts for sysadmin use, and not a lot of end-user or back-end applications. doing `print(f"{workstation} :: Copying {src} to {dst}...", end='', flush=True); ok = copy_the_thing(src, dst); if ok: print("SUCCESS!")` is FANTASTIC. – Adam Smith Aug 15 '17 at 20:09