Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping quotation marks in f string interpolation

I can't get to include quotation marks in the following string interpolator:

f"foo ${math.abs(-0.9876f)*100}%1.1f%%"

The output is

foo 98.8%

Now the desired output is

foo "98.8%"

Inserting \" doesn't work, only produces "unclosed string literal" errors.

like image 385
0__ Avatar asked Jun 13 '13 10:06

0__


People also ask

How do you escape quotation marks?

Alternatively, you can use a backslash \ to escape the quotation marks.

How do you ignore quotes in a string?

The backslash character allows us to escape the single quote, so it's interpreted as the literal single quote character, and not as an end of string character. You can use the same approach to escape a double quote in a string. Copied! We use the backslash \ character to escape each double quote in the string.

What is f {} in Python?

“F-strings provide a way to embed expressions inside string literals, using a minimal syntax. It should be noted that an f-string is really an expression evaluated at run time, not a constant value. In Python source code, an f-string is a literal string, prefixed with f , which contains expressions inside braces.

What is F before quotes in Python?

In Python source code, an f-string is a literal string, prefixed with 'f', which contains expressions inside braces. The expressions are replaced with their values. Some examples are: >>> import datetime >>> name = 'Fred' >>> age = 50 >>> anniversary = datetime.


1 Answers

Seems that this problem wouldn't be fixed. You can use one of the following workarounds:

  1. multi-line strings:

    f"""foo "${math.abs(-0.9876f)*100}%1.1f%""""

  2. \042:

    f"foo \042${math.abs(-0.9876f)*100}%1.1f%\042"

  3. ${'"'}:

    f"foo ${'"'}${math.abs(-0.9876f)*100}%1.1f%${'"'}"

like image 78
tenshi Avatar answered Oct 02 '22 19:10

tenshi