I would like to format a string x
using string-literals (python 3.6+) obtaining the precision from a variable n
.
def strtrunc(x, n):
return(f'{x:.ng}')
Found the answer myself while writing the question: Variables in string formatting can be nested as follows (seen in Format string in python with variable formatting), also works for string-literals:
def strtrunc(x, n):
return(f'{x:.{n}g}')
strtrunc(x=12.34534, n=5)
Out[188]: '12.345'