2

I'm loving the new f-Strings in python 3.6, but I'm seeing a couple issues when trying to return a String in the expression. The following code doesn't work and tells me I'm using invalid syntax, even though the expression itself is correct.

print(f'{v1} is {'greater' if v1 > v2 else 'less'} than {v2}') # Boo error

It tells me that 'greater' and 'less' are unexpected tokens. If I replace them with two variables containing the strings, or even two integers, the error disappears.

print(f'{v1} is {10 if v1 > v2 else 5} than {v2}') # Yay no error

What am I missing here?

Girrafish
  • 2,320
  • 1
  • 19
  • 32
  • The syntax highlighting in your editor or even here on StackOverflow is a clue as well :) – Tim Pietzcker Dec 04 '18 at 09:35
  • Does this answer your question? [Invalid Syntax when F' string dictionary](https://stackoverflow.com/questions/57876137/invalid-syntax-when-f-string-dictionary) – user202729 Feb 12 '21 at 13:38

3 Answers3

6

You must still respect rules regarding quotes within quotes:

v1 = 5
v2 = 6

print(f'{v1} is {"greater" if v1 > v2 else "less"} than {v2}')

# 5 is less than 6

Or possibly more readable:

print(f"{v1} is {'greater' if v1 > v2 else 'less'} than {v2}")

Note that regular strings permit \', i.e. use of the backslash for quotes within quotes. This is not permitted in f-strings, as noted in PEP498:

Backslashes may not appear anywhere within expressions.

jpp
  • 159,742
  • 34
  • 281
  • 339
3

Just mix the quotes, check howto Formatted string literals

print(f'{v1} is {"greater" if v1 > v2 else "less"} than {v2}')
Juan Diego Godoy Robles
  • 14,447
  • 2
  • 38
  • 52
0

Quotation marks cause the error.

Use this:

print(f'{v1} is {"greater" if v1 > v2 else "less"} than {v2}') 
Rarblack
  • 4,559
  • 4
  • 22
  • 33