【发布时间】:2016-07-12 20:28:51
【问题描述】:
我在 python2 中有一个程序,但是,我正在用 python3 重写它。我读入了一个 netcdf 文件,并保存了变量。其中一个变量应该是一个字符串,我需要将该字符串转换为一个整数。在 python 2 中,我使用这种方法:
nums = fid.variables['num'][:]
>>> nums[0]
>>> ['0','1','2','3']
Number = [int(''.join(t)) for t in nums]
>>> Number[0]
>>> 123
但是,在 python 3 中,变量“nums”输出:
>>>nums[0]
>>>[b'0',b'1',b'2',b'3']
我得到了错误:
TypeError: sequence item 0: expected str instance, numpy.bytes_ found
为了将类型从字节更改为字符串,我尝试过:
newNum = [t.decode('UFT-8') for t in nums]
但我得到了错误:
AttributeError: 'numpy.ndarray' object has no attribute 'decode'
问题:
如何将字母和数字的字符串变成整数?
【问题讨论】:
-
我无法在 python 2.7 中重现您的原始行为
-
错误是什么?
-
ValueError: invalid literal for int() with base 10: 'FS0123' -
我很抱歉,这是我的错误,变量 nums 都是数字 - 请参阅上面的编辑
-
对了,我很好奇
nums[0]是一个numpy数组,因为这个:[b'F',b'S',b'0',b'1',b'2',b'3']代表一个字节列表。无论如何,您将无法解码容器,因此您需要newNum = [n.decode('utf8') for t in nums for n in t]
标签: python string numpy integer byte