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

yipeiwu_com6年前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中内置了很多的函数和类,在自己定义变量的时候,切记不要覆盖或者和他们的名字重复。

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

相关文章

Windows 8.1 64bit下搭建 Scrapy 0.22 环境

Windows 8.1 64bit下搭建 Scrapy 0.22 环境

我的Windows 8.1 环境 1.下载安装Python 2.7.6 在Python官方网站中下载Python2.7.6的Windows安装包,根据默认配置安装到C:\Python2...

创建Shapefile文件并写入数据的例子

创建Shapefile文件并写入数据的例子

基本思路 使用GDAL创建Shapefile数据的基本步骤如下: 使用osgeo.ogr.Driver的CreateDataSource()方法创建osgeo.ogr.DataSourc...

Python PIL图片添加字体的例子

Python PIL图片添加字体的例子

效果 左边原图,右面添加字体后保存的图。 代码 # -*- coding: utf-8 -*- import PIL.Image as Image import PIL.Image...

python 字典中文key处理,读取,比较方法

python 字典中文key处理,读取,比较方法

昨天碰到的,如果键是中文,如何进行匹配呢,先看文本内容: 这是字典里两个元素的内容,编码是utf-8,中文内容 运行代码如下 # -*- coding: utf-8 -*-...

探究python中open函数的使用

探究python中open函数的使用

最近,开始学习python的开发,遇到了一点文件操作的问题,探究一下open函数的使用。 一、open()的函数原型 open(file, mode=‘r', buffering=-1,...