简体   繁体   中英

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

I am new to Python and I am trying to write a simple print function but I am getting a strange error. This is my code:

#! /usr/bin/env python3.2
import numpy as np

a=np.arange(1,10,1)
print(a)
for i in a:
    print(i)
    print(type(i))
    print("{0:<12g}".format(i))

The output is:

[1 2 3 4 5 6 7 8 9]
1
<class 'numpy.int64'>
Traceback (most recent call last):
  File "./test.py", line 9, in <module>
    print("{0:<12g}".format(i))
ValueError: Unknown format code 'g' for object of type 'str'

Why does print take the "numpy.int64" as a string? I have to add that it works perfectly for a normal list: (eg [1,2,3,4]) I would be most grateful to any ideas on this issue, thanks ;-).

This is a known bug and should be fixed in version 2.0. In the interim, you can use the old syntax %f that works.

Someone will be able to give you a more in-depth answer, but what I think is happening here is that you're using "{0:<12g}".format(i) which uses special formatting. If you'd try "\\{{0}:<12g\\}".format(i) you'd probably get better results. Using the slashes there escapes the {} 's which is what is giving you the error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM