0

Question question regarding f-strings and expressions in Python 3.

The Python documentation states clearly that:

Formatted string literals (also called f-strings for short) let you include the value of Python expressions inside a string by prefixing the string with f or F and writing expressions as {expression}.

A valid expression is: {A = "A"} but this doesn't work:

>>> print(f'{A = "A"} {A}')
    File "main.py", line 3
    print(f'{A = "A"} {A}')
          ^
SyntaxError: f-string: expecting '}'

What am I doing wrong here? My expression is valid. I'm sure I'm misunderstanding the documentation so if someone can clarify it would be a great help.

Thanks.

4
  • "A valid expression is: {A = "A"} [...] My expression is valid." assignment is not a valid python expression. Commented Dec 27, 2023 at 16:05
  • @Masklinn You're correct. Thank you. I was frantically googling around and come across this: codepict.com/expressions-and-statements-in-python Which wrongfully states: "So, the first combination x = 5 is an expression" Commented Dec 27, 2023 at 16:09
  • @DavisHerring Yes that helps, thank you. Does the Python documentation have a list of what does and does not constitute an expression? Each language seems to define what is and isn't one differently and it's causing me a real headache. Commented Dec 27, 2023 at 16:11
  • 2
    @the_slug: Of course it does—it’s a bit technical, of course, since it’s a reference rather than a tutorial, but anything’s better than the nonsense you found! Commented Dec 27, 2023 at 16:14

1 Answer 1

0

You probably want to do this: print(f'A = {A}')

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.