python - 类型错误 : Must be str not int

标签 python string floating-point int

我正在使用此代码连接具有浮点值的字符串:

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/

相关文章:

c - 编写我自己的 float 解析器

java - 在 Java 中 parseFloat 的正确方法是什么

python - 无法从 HTTP POST 请求恢复项目列表

python : How to add month to December 2012 and get January 2013?

python - 将字符串转换为元组

c - 为什么 C 给我的答案与我的计算器不同?

python - .apply 如何在 Pandas DataFrame.groupby 上工作?

Python csv : Split column to columns and then to rows by delimiter

python - 查找字符串中出现的所有字符

database - Fortran - 提取仅包含指定字符的字符串