Python: How to evaluate a function which is string?

前端 未结 5 1990
悲&欢浪女
悲&欢浪女 2021-01-16 23:22

I get some models from database as

f(t)=(2.128795454425367)+(208.54359721863273)*t+(26.098128487929266)*t^2+(3.34369909584111)*t^3+(-0.3450228278737971)*t^4+         


        
5条回答
  •  温柔的废话
    2021-01-16 23:34

    if you trust your sources you can do it like this with regex and eval:

    # deletes the simicolon and everything before the space
    my_str = start_str.split('=')[1][:-1]
    # change ^ to ** because that's the squared operator
    my_str = re.sub('\^', '**', my_str)
    # substitute the t for the numbers 1 to 13 and evaluate the string
    results = [eval(re.sub('t', str(t), my_str)) for t in range(1,13)]
    

提交回复
热议问题