Python str is not callable problem details and solutions

  • 2020-05-26 09:31:00
  • OfStack

str is not callable problem details and solutions

Questions raised:

In the code of Python, an error message was encountered during the process of running:

python code:


def check_province_code(province, country): 
  num = len(province) 
   
  while num <3: 
    province = ''.join([str(0),province]) 
    num = num +1 
   
  return country + province 

Running error message:


check_province_code('ab', '001') 
--------------------------------------------------------------------------- 
TypeError                 Traceback (most recent call last) 
<ipython-input-44-02ec8a351cce> in <module>() 
----> 1 check_province_code('ab', '001') 
 
<ipython-input-43-12db968aa80a> in check_province_code(province, country) 
   3  
   4   while num <3: 
----> 5     province = ''.join([str(0),province]) 
   6     num = num +1 
   7  
 
TypeError: 'str' object is not callable  

Problem analysis and troubleshooting:

From the error message analysis, str is not a callable object, but it can be called before, and in python's api document, it is a built-in function of python, why can't it be used?

So let's go ahead and verify 1.

Execute str(123) from the command line, converting the number to string:


>>> str(1233) 
--------------------------------------------------------------------------- 
TypeError                 Traceback (most recent call last) 
<ipython-input-45-afcef5460e92> in <module>() 
----> 1 str(1233) 
 
TypeError: 'str' object is not callable  

This problem is clearly defined, str was not there before, but if you think about it carefully, str was used randomly when you defined variables, so str function was overwritten. The following operations were performed:


str = '123' 

Restore the default str function

Restart the python application for 1, and remove the part of the code covered by str.

conclusion

There are many functions and classes built into python. When you define your own variables, be sure not to overwrite or duplicate their names.

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: