Python中str is not callable问题详解及解决办法

yipeiwu_com5年前Python基础

Python中str is not callable问题详解及解决办法

问题提出:

   在Python的代码,在运行过程中,碰到了一个错误信息:

   python代码:

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

  运行的错误信息:

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  

问题分析与排查:

   从错误信息分析, str不是一个可调用的对象,可是之前确实可以调用的,且在python的api文档中,其是python内置的一个函数呀, 怎么不能用了呢?

 还是继续验证一下吧。

   在命令行下执行str(123),将数字转换为string:

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

 这下问题定义清楚了,原来没有了str,仔细想了想原来刚才在定义变量的时候,随机使用str,所以就被覆盖了str函数。进行了类似以下的操作:

str = '123' 

恢复默认的str函数

   重新启动一下python应用,移除str被覆盖的代码部分即可。

总结

  在python中内置了很多的函数和类,在自己定义变量的时候,切记不要覆盖或者和他们的名字重复。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

相关文章

Python遍历目录的4种方法实例介绍

1.os.popen运行shell列表命令 复制代码 代码如下: def traverseDirByShell(path):     for f in os...

Python中的zipfile模块使用详解

zip文件格式是通用的文档压缩标准,在ziplib模块中,使用ZipFile类来操作zip文件,下面具体介绍一下: class zipfile.ZipFile(file[, mode[,...

pytorch神经网络之卷积层与全连接层参数的设置方法

当使用pytorch写网络结构的时候,本人发现在卷积层与第一个全连接层的全连接层的input_features不知道该写多少?一开始本人的做法是对着pytorch官网的公式推,但是总是算...

简单介绍Python的轻便web框架Bottle

基本映射 映射使用在根据不同URLs请求来产生相对应的返回内容.Bottle使用route() 修饰器来实现映射. from bottle import route, run@rou...

Python二叉搜索树与双向链表转换实现方法

本文实例讲述了Python二叉搜索树与双向链表实现方法。分享给大家供大家参考,具体如下: # encoding=utf8 ''' 题目:输入一棵二叉搜索树,将该二叉搜索树转换成一个排...