'How to mix f-string and LaTeX symbols in a print(...) statement? [duplicate]

I am calculating pi with the Monte Carlo "quarter circle" method, using the following program:

from random import random as rd

def estimPi(n_points):
    counter = 0
    for i in range(n_points):
        x,y = rd(),rd()
        if x**2 + y**2 < 1:
            counter = counter + 1
    estimPi = 4*(counter/n_points)

    print(f'with {n_points} draws, the estimated value of pi is {estimPi}')

So that:

estimPi(10000)

gives me (as an example, of course):

with 10000 draws, the estimated value of pi is 3.1304

I would like to modify the print(...) line in order to have the pi symbol in the text printed, instead of having the string "pi".

I tried:

print(f'with {n_points} draws, the estimated value of ' + r'$ \pi $' + f' is {estimPi}')

but it doesn't give me what I expect:

with 10000 draws, the estimated value of $ \pi $ is 3.1276

Is there a way to mix f-strings and LaTeX symbols in a print(...)?



Solution 1:[1]

Why not use the unicode symbol for that?

    print(f'with {n_points} draws, the estimated value of \u03C0 is {estimPi}')

output: with 10000 draws, the estimated value of ? is 3.1164

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Marcin Cuprjak