Ask Your Question

Sage doesn't support completely modern string formatting

asked 2020-03-04 01:09:36 +0200

dsejas gravatar image

Hello, Sage community!

Modern Python 3 defines various way to printing formatted strings. Here are some examples:

myconst = N(3/8)
print('Hello, world of %.2f'%(myconst))
print('Hello, world of {:.2f}'.format(myconst))
print(f'Hello, world of {myconst:.2f}')

The first example should be the most known and common. The second example uses the format method, and the third uses f-strings. Unfortunately, these two last forms of formatted strings aren't supported by Sage. For example,

print('Hello, world of {:.2f}'.format(myconst))

prints the following traceback

TypeError                                 Traceback (most recent call last)
<ipython-input-6-6336f0c43d90> in <module>()
----> 1 print('Hello, world of {:.2f}'.format(myconst))

TypeError: unsupported format string passed to sage.rings.real_mpfr.RealNumber.__format__

Exactly the same error and traceback are issued with the third example.

Now, on the other hand, if no string conversion specification is used, these work fine:

print('Hello, world of {}'.format(myconst))
print(f'Hello, world of {myconst}')

Also, try using pi instead of myconst. Works fine withN(pi), but not with N(myconst); this seems an inconsistent behavior.

Is there some workaround for this problem? Should it be reported as a bug/enhancement?

edit retag flag offensive close merge delete


If you replace myconst = N(3/8) by myconst = float(3/8), there is no error. SageMath supports the three kinds of formatting, but unfortunately not for all data types.

Juanjo gravatar imageJuanjo ( 2020-03-04 09:49:22 +0200 )edit

Thank you very much, @Juanjo and @eric_g! I suppose this is a matter of implementing the __format__ special method for these data types.

For now, I'm leaving the question open. But maybe the bug track is a good answer. If @eric_g decides to post it as answer, I can tick the question as answered.

dsejas gravatar imagedsejas ( 2020-03-04 17:19:54 +0200 )edit

1 Answer

Sort by ยป oldest newest most voted

answered 2020-03-04 16:17:46 +0200

eric_g gravatar image

This bug is being tracked at

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2020-03-04 01:09:36 +0200

Seen: 369 times

Last updated: Mar 04 '20