Ask Your Question
0

sage thinks a float is a string

asked 7 years ago

cybervigilante gravatar image

updated 7 years ago

x = 42.44444

print("all {2:.3f} good {0} eat {1}".format("dogs","shoes",x))

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

This is Sage in Linux Mint

Preview: (hide)

Comments

BTW, why am I not getting line breaks between the x value and the print. I tried preformat and I still don't get them.

cybervigilante gravatar imagecybervigilante ( 7 years ago )

In my experience, you can't have a code block as the first thing.

John Palmieri gravatar imageJohn Palmieri ( 7 years ago )

Correct, that is perhaps a bug in the markdown (https://github.com/trentm/python-mark...) similar to https://github.com/trentm/python-mark... which is noted at https://askbot.org/en/question/2732/f...

kcrisman gravatar imagekcrisman ( 7 years ago )

2 Answers

Sort by » oldest newest most voted
0

answered 7 years ago

ndomes gravatar image

This works for me:

print("all {4:{0}.{1}} good {2} eat {3}".format(2,6,"dogs","shoes",x))
Preview: (hide)
link

Comments

Or print("all {2:2.6} good {0} eat {1}".format("dogs","shoes",x))

John Palmieri gravatar imageJohn Palmieri ( 7 years ago )
0

answered 7 years ago

This works for me:

x = float(42.44444)
print("all {2:.3f} good {0} eat {1}".format("dogs","shoes",x))

With your code, x is not a float:

x = 42.44444
sage: type(x)
<type 'sage.rings.real_mpfr.RealLiteral'>

I guess not all aspects of Python's format are implemented for this type of object. Perhaps it passes the string representation of x to format, which is what leads to the error message.

Preview: (hide)
link

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

Stats

Asked: 7 years ago

Seen: 1,027 times

Last updated: Jun 04 '17