0

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}')
NicoH
  • 1,240
  • 3
  • 12
  • 23

1 Answers1

0

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'
NicoH
  • 1,240
  • 3
  • 12
  • 23