我正在使用此代码连接具有浮点值的字符串:
fr = channel.freqhz / 1000000
print ("fr type is", type(fr))
rx_channel = "<RxChannel>\n\
<IsDefault>1</IsDefault>\n\
<UsedForRX2>" + channel.usedforrx2 + "</UsedForRX2>\n\
<ChIndex>" + str(i) + "</ChIndex>\n\
<LC>" + str(channel.index) + "</LC>\n\
<SB>" + channel.subband + "</SB>\n\
<DTC>100</DTC>\n\
<Frequency>" + str(fr) + "</Frequency>\n\
<MinDR>0</MinDR>\n\
<MaxDR>5</MaxDR>\n\
</RxChannel>\n"
但我收到此错误消息:
> fr type is <class 'float'>
> Traceback (most recent call last):
> File "createRFRegion.py", line 260, in <module>
> write_rf_region(rf_region_file, rf_region_filename)
> File "createRFRegion.py", line 233, in write_rf_region
> rf_region_file.write(create_rx_channel(channel, i))
> File "createRFRegion.py", line 164, in create_rx_channel
> <Frequency>" + str(fr) + "</Frequency>\n\
> TypeError: must be str, not int
我不明白这个错误,因为我正在使用 str() 函数将 float 转换为 str。
最佳答案
只需在所有字段中使用str()
。
Python 对多行操作和错误的处理不是很好,会指向多行操作的最后一行(我假设它是把最后一行的所有字符串拼在一起,从而指向在 str(fr)
).
字段 fr
甚至不是 int
,它是 float
,因此错误来自其他字段之一。我的猜测是 channel.subband
, channel 的子带将是一个整数。
rx_channel = "<RxChannel>\n<IsDefault>1</IsDefault>\n<UsedForRX2>" +
str(channel.usedforrx2) + "</UsedForRX2>\n<ChIndex>" +
str(i) + "</ChIndex>\n<LC>" +
str(channel.index) + "</LC>\n<SB>" +
str(channel.subband) + "</SB>\n<DTC>100</DTC>\n<Frequency>" +
str(fr) + "</Frequency>\n<MinDR>0</MinDR>\n<MaxDR>5</MaxDR>\n/RxChannel>\n"
关于python - 类型错误 : Must be str not int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44287256/