Google Groups

Re: Using Python new style string formatting in Sage


Zoresvit Mar 24, 2012 5:53 PM
Posted in group: sage-support
Thanks a lot! Always forgetting Sage has its own type for integers. Some automatic coersion would help a lot in such situation.

On Wednesday, March 7, 2012 2:02:17 PM UTC+2, Jason Grout wrote:
On 3/7/12 5:50 AM, Zoresvit wrote:
> Is there a way to use new Python string formatting
> <http://docs.python.org/​library/string.html> in Sage without disabling
> the preparser?
>
> For now I get the following:
>
>     sage: "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42)
>     ------------------------------​------------------------------​---------------
>     ValueError Traceback (most recent call last)
>     /home/zoresvit/devel/​ciphering/algebraic/<ipython console> in <module>()
>     ValueError: Unknown format code 'd' for object of type 'str'
>
>
> If the preparser is off, everything works:
>
>     sage: preparser(False)
>     sage: "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42)
>     'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010'
>

The problem is that apparently format doesn't accept Integers:

sage: "int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(int(42))
'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010'
sage: "int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin:
{0:#b}".format(Integer(42))
------------------------------​------------------------------​---------------
ValueError                                Traceback (most recent call last)

/Users/grout/jason/drake/​linear-algebra/Exams/<ipython console> in
<module>()

ValueError: Unknown format code 'd' for object of type 'str'

Thanks,

Jason