TypeError:'str'对象不可调用(我没有调用它?) [英] TypeError: 'str' object is not callable (I'm not calling it?)
本文介绍了TypeError:'str'对象不可调用(我没有调用它?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
$ b $我试图用一个函数写入一个文件,其中有4个不同的字符串变量传递到写入的文件中,但无论出于何种原因, b
Traceback(最近一次调用最后一次):
在< module>中的第34行中的C:\Python Files\writePy\writePy.py文件;
indent = writeIf(mFile,genCond(),lFile,indent)
在writeIf
文件中的第23行文件C:\Python Files\writePy\writePy.py .write('%sif(%s%s%s):'(indentation,cond [0],cond [1],cond [2]))
TypeError:'str'对象不可调用
这是我的主要代码:
#主代码
lFile = open('OperationLog.txt',mode ='w')#记录文件以进行更改
mFile = open('Evolve.txt',mode ='w +')#要编辑的文件
indent = 0#写入代码的缩进
#将两个带有随机条件的IF语句写入文件,更新缩进
indent = writeIf(mFile,genCond(),lFile,indent)
indent = writeIf(mFile,genCond(),lFile,indent)
#关闭文件
lFile.close()
mFile.close()
这是错误的函数: p>
def writeIf(file,cond,log,indent):
indentation = ''*(4 * indent)#要添加的空格的数量是4 * indent
file.write('%sif(%s%s%s):'(indentation,cond [0],cond [1 ],cond [2]))
indent = indent + 1
log.write('添加:IF语句到%s。'%file.name)
返回缩进
解决方案使用
格式()
b $ b $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $'$> {1} {2} {3}):'。format(indentation,cond [0],cond [1],cond [2]))
I'm trying to have a function write to a file with 4 different string variables passed into what is written, but for whatever reason when this is attempted, I get this:
Traceback (most recent call last):
File "C:\Python Files\writePy\writePy.py", line 34, in <module>
indent = writeIf(mFile, genCond(), lFile, indent)
File "C:\Python Files\writePy\writePy.py", line 23, in writeIf
file.write('%sif (%s %s %s):' (indentation, cond[0], cond[1], cond[2]))
TypeError: 'str' object is not callable
This is my main code:
# Main code
lFile = open('OperationLog.txt', mode='w') # Log file for changes
mFile = open('Evolve.txt', mode='w+') # File to be edited
indent = 0 # Indentation for written code
# Write two IF statements with a randomized condition to file, update indentation
indent = writeIf(mFile, genCond(), lFile, indent)
indent = writeIf(mFile, genCond(), lFile, indent)
# Close files
lFile.close()
mFile.close()
and this is the function the error is in:
def writeIf(file, cond, log, indent):
indentation = ' ' * (4 * indent) # Number of spaces to add is 4 * indent
file.write('%sif (%s %s %s):' (indentation, cond[0], cond[1], cond[2]))
indent = indent + 1
log.write('Added: IF statement to %s.' % file.name)
return indent
解决方案
Use the format()
function in cases as this as its more suitable and easy to maintain
file.write('{0}if ({1}{2}{3}):'.format(indentation, cond[0], cond[1], cond[2]))
这篇关于TypeError:'str'对象不可调用(我没有调用它?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文