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.
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}}}}}'.
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.
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.
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 { }.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With