1

I currently have this code here:

test = 2.432
test_formatted = "{:.2f}".format(test)
print(test_formatted)

Output:

2.43

Is there a way to insert a variable for the number into the format string? Such as:

test = 2.432
te = 2
test_formatted = "{:." + str(te) + "f}".format(test)
print(test_formatted)

Thanks!

2
  • 1
    Do you mean f-strings? f"{te:.2f}" I'm not sure what your expected result is, can you explain? Commented Jun 9, 2020 at 21:06
  • Sorry, I misunderstood for a sec. The f string trick appears to work for me, thanks. Commented Jun 9, 2020 at 21:19

3 Answers 3

3

Like this:

'{{:.{}f}}'.format(te)
# Result: '{:.2f}'

Or directly convert the number with an f-string (Python 3.6 and newer):

f'{test:.{te}f}'
# Result: '2.43'
Sign up to request clarification or add additional context in comments.

2 Comments

It prints the result but in quotes: '2.432'
Use it as the argument for print() or assign it to a variable.
2

Add some parenthesis around the string you are creating and it works!

test = 2.432
te = 3
test_formatted = ("{:." + str(te) + "f}").format(test)
print(test_formatted)

1 Comment

It works just fine in regular Python, but not in discord.py: discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ValueError: Single '}' encountered in format string
1

Using f-strings, you can do something like this:

test = 2.432
te = 2
test_formatted = f"{test:.{te}f}"
print(test_formatted)

Output:

2.43

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.