Search code examples
pythonstringpython-3.xf-string

Invalid syntax - Expression returning a string in f-String


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?


Solution

  • 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.