类型错误:必须是str而不是in

2024-04-27 15:13:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用此代码将字符串与浮点值连接起来:

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


Tags: inpyistypelinechannelfrrx
2条回答

什么是channel.usedforrx2channel.subband的值?我怀疑其中一个是int而不是string。另外,为了使代码更具可读性,请考虑将该语句替换为:

rx_channel = """<RxChannel>
  <IsDefault>1</IsDefault>
  <UsedForRX2>{}</UsedForRX2>
  <ChIndex>{}</ChIndex>
  <LC>{}</LC>
  <SB>{}</SB>
  <DTC>100</DTC>
  <Frequency>{}</Frequency>
  <MinDR>0</MinDR>
  <MaxDR>5</MaxDR>
</RxChannel>
""".format(channel.usedforrx2, i, channel.index, channel.subband, fr)

只需在所有字段中使用str()

Python不能很好地处理多行操作和错误,它将指向多行操作的最后一行(我假设它将最后一行中的所有字符串连接在一起,从而指向str(fr))。

字段fr甚至不是int,而是float,因此错误来自其他字段之一。我的猜测是channel.subband,一个通道的子带将是一个整数。

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"

相关问题 更多 >