Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python fstring as function

I'd like to use Python f-string for its syntactical simplicity, compared to string.Template() or other approach. However, in my application, the string is loaded from file, and the values of the variable can only be provided later.

If there a way to invoke fstring functionality separate from the string definition? Hopefully code below will better explain what I hope to achieve.

a = 5
s1 = f'a is {a}' # prints 'a is 5'

a = 5
s2 = 'a is {a}'
func(s2) # what should be func equivalent to fstring
like image 571
idazuwaika Avatar asked Dec 01 '17 16:12

idazuwaika


2 Answers

By using eval() and passing either locals() or any arbitrary dict as the second positional locals argument, you can calculate an f-string dynamically on the fly with any combination of inputs.

def fstr(fstring_text, locals, globals=None):
    """
    Dynamically evaluate the provided fstring_text
    """
    locals = locals or {}
    globals = globals or {}
    ret_val = eval(f'f"{fstring_text}"', locals, globals)
    return ret_val

Sample usage:

format_str = "{i}*{i}={i*i}"
i = 2
fstr(format_str, locals()) # "2*2=4"
i = 4
fstr(format_str, locals()) # "4*4=16"
fstr(format_str, {"i": 12}) # "10*10=100"
like image 54
aaronsteers Avatar answered Oct 12 '22 16:10

aaronsteers


Here's what you were looking for:

pip install fstring

from fstring import fstring

x = 1

y = 2.0

plus_result = "3.0"

print fstring("{x}+{y}={plus_result}")

# Prints: 1+2.0=3.0
like image 39
RinSlow Avatar answered Oct 12 '22 16:10

RinSlow