Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

f-string formula inside curly brackets not working

I am on Python 3.7.

My code on line 3 works fine, however when I insert the underlying formula into line 4, my code returns the error:

SyntaxError: f-string: mismatched '(', '{', or '[' (the error points to the first '(' in line 4.

My code is:

cheapest_plan_point = 3122.54
phrase = format(round(cheapest_plan_point), ",")
print(f"1: {phrase}")
print(f"2: {format(round(cheapest_plan_point), ",")}")

I can't figure out what is wrong with line 4.

like image 607
Deskjokey Avatar asked Oct 03 '18 13:10

Deskjokey


People also ask

How do you use curly brackets in F string?

If you need to keep two curly braces in the string, you need 5 curly braces on each side of the variable. @TerryA there isn't a difference in brace behavior between . format and f-strings. The code a = 1; print('{{{{{a}}}}}'.

How do you write curly braces in F string Python?

If you have multiple variables in the string, you need to enclose each of the variable names inside a set of curly braces. The syntax is shown below: f"This is an f-string {var_name} and {var_name}." ▶ Here's an example.

What do {} do in Python?

In languages like C curly braces ( {} ) are used to create program blocks used in flow control. In Python, curly braces are used to define a data structure called a dictionary (a key/value mapping), while white space indentation is used to define program blocks.

How do I escape an F string in Python?

We can use any quotation marks {single or double or triple} in the f-string. We have to use the escape character to print quotation marks. The f-string expression doesn't allow us to use the backslash. We have to place it outside the { }.


1 Answers

You used " quotes inside a "..." delimited string.

Python sees:

print(f"2: {format(round(cheapest_plan_point), "
      ,
      ")}")

so the )} is a new, separate string.

Use different delimiters:

print(f"2: {format(round(cheapest_plan_point), ',')}")

However, you don't need to use format() here. In an f-string, you already are formatting each interpolated value! Just add :, to apply the formatting instruction directly to the round() result:

print(f"2: {round(cheapest_plan_point):,}")

The format {expression:formatting_spec} applies formatting_spec to the outcome of expression, just as if you used {format(expression, 'formatting_spec')}, but without having to call format() and without having to put the formatting_spec part in quotes.

like image 123
Martijn Pieters Avatar answered Sep 30 '22 17:09

Martijn Pieters