簡體   English   中英

TypeError:“ str”對象不可調用

[英]TypeError: 'str' object is not callable

我正在嘗試生成一個將其轉換為int的隨機數,然后打印該數字,但是我收到錯誤消息“ str”對象不可調用。 我用谷歌搜索了問題,但似乎找不到我做錯了什么。

這是我的代碼:

import random
import time

while(True):
    #generate a random frequency from 0Hz to 1MHz   
    frequency = int(random.randrange(0,1000000))    
    print('Frequency: %d'('frequency'))
    print('Frequency: ',frequency, ' Hz')

    print("sleep for 2 seconds")
    time.sleep(2)  # Delay for 1 minute (60 seconds)

我得到的錯誤是:

Traceback(most recent call last):
File "frequency1.py", line 7, in <module>
print('Frequency: %d'('Frequency'))
TypeError: 'str' object is not callable

您的打印聲明不正確。 應該是

print('Frequency: %d'%(frequency))

當您執行'Frequency: %d'(frequency) ,您試圖將字符串'Frequency: %d'作為函數調用。 這就是為什么會出現錯誤TypeError: 'str' object is not callable 可以將錯誤解碼為'str' object ,即'Frequency: %d'不可調用,即它不是可以調用的函數

您可以嘗試format因為它更好。 請閱讀PEP-3101 ,其中提到了format%運算符。 打印聲明可以寫成

print('Frequency: {}'.format(frequency))

糾正丟失的%符號后,更改后的程序可以寫為

import random
import time

while(True):
    #generate a random frequency from 0Hz to 1MHz   
    frequency = int(random.randrange(0,1000000))    
    print('Frequency: %d'%(frequency))            # Note the added % 
    print('Frequency: ',frequency, ' Hz')

    print("sleep for 2 seconds")
    time.sleep(2)  # Delay for 1 minute (60 seconds)

該程序在執行時將給出以下輸出。

Frequency: 753865
Frequency:  753865  Hz
sleep for 2 seconds
Frequency: 152017
Frequency:  152017  Hz
sleep for 2 seconds

還要注意的是,在Python添加一個空格。 因此,您無需執行print('Frequency: ',frequency, ' Hz') ,而可以直接編寫print('Frequency:',frequency, 'Hz')

字符串插值是使用%運算符完成的,但是您試圖像對待函數一樣調用該字符串,它解釋了錯誤。

它應該是:

print("Frequency: %d" % frequency)

請注意,如果有多個值, %的右側僅需為一個元組,可以像上面那樣裸露地傳遞單個值。

另外,在Python 3中,更現代的format()語法更常見:

printf("Frequency: {}".format(frequency))
>>> while(True):
...     frequency = int(random.randrange(0,1000000))    
...     print('Frequency: %d'%frequency)
...     print('Frequency: ',frequency, ' Hz')
...     time.sleep(2)  # Delay for 1 minute (60 seconds)

...

輸出量

頻率:720460('頻率:',720460,'Hz')

頻率:559979('頻率:',559979,'Hz')

頻率:649103('頻率:',649103,'Hz')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM