0

This code:

a = 10
b = 20
print(f "The variable a is {a} and the variable b is {b}.")

returns this error:

File "main.py", line 3                                                                                          
    print (f "The variable a is {a} and the variable b is {b}")                                                   
                                                             ^                                                    
SyntaxError: invalid syntax

The version I'm using is after 3.6, so it should work. I'm using Anaconda's prompt, if that's a problem.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Vijay Shastri
  • 53
  • 1
  • 5
  • 4
    remove the space. It should be `f"...` not `f "` – Tomerikoo May 24 '20 at 21:18
  • 3
    To elaborate: `f "..."` has to mean the variable named `f`, followed by the string literal `'...'`, because it is two separate tokens. It is a syntax error for the same reason that `x 4` would be a syntax error: it's just two separate expressions with no operator connecting them. Without the space, the parser can treat `f"..."` as a single thing, and then apply the special rules to understand what that f-string means. – Karl Knechtel May 24 '20 at 21:27

2 Answers2

1

you have a space between f and the string. Remove it and everything will work.

The syntax error points to the end of the string. If it pointed to the beginning of the string it would give you a better hint at the problem: after the f, which is interpreted as a variable in this case, a string is unexpected.

Walter Tross
  • 12,237
  • 2
  • 40
  • 64
-2

You need this:

a = 1
b = 2

test_str = f"{'The variable a is'} {a} {'and the variable b is '}{b}"
print(test_str)

Between the curly braces, string interpolation takes place. The variables for a and b are within two of the curly brace sets and hard-coded strings are within the other two.

Wayne Lambert
  • 576
  • 5
  • 9
  • 2
    Why use placeholders for literal strings? The other two sets of curly braces are not necessary and make things harder to read. In fact, OP's string is perfectly fine except for that space between the `f` and the string itself – Tomerikoo May 24 '20 at 21:41
  • @Tomerikoo You're absolutely right, you don't need to. I guess I was trying to use a contrived example to explain that you can interpolate literal values like the strings in addition to variables. It is indeed more succinct and better practice without the braces as placeholders. – Wayne Lambert May 24 '20 at 21:44