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}')

1 Answer 1

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'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.