Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid syntax - Expression returning a string in f-String [duplicate]

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?

like image 471
Girrafish Avatar asked Nov 19 '25 10:11

Girrafish


2 Answers

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.

like image 118
jpp Avatar answered Nov 21 '25 23:11

jpp


Just mix the quotes, check howto Formatted string literals

print(f'{v1} is {"greater" if v1 > v2 else "less"} than {v2}')
like image 45
Juan Diego Godoy Robles Avatar answered Nov 22 '25 00:11

Juan Diego Godoy Robles



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!