Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sql-server-2005/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 当我运行此命令时,我发现TypeError:“str”对象不可调用。。为什么呢?_Python - Fatal编程技术网

Python 当我运行此命令时,我发现TypeError:“str”对象不可调用。。为什么呢?

Python 当我运行此命令时,我发现TypeError:“str”对象不可调用。。为什么呢?,python,Python,这就是我要回来的 def ceasarEncipher(pt,key): for i in range(0,len(pt)): ct="" currentChar=pt(i) numericChar=ord(currentChar)-ord('a') numericNewChar=(numericChar+key)% 26 numbericNewChar=numericChar + ord('a')

这就是我要回来的

def ceasarEncipher(pt,key):
    for i in range(0,len(pt)):
        ct=""
        currentChar=pt(i)
        numericChar=ord(currentChar)-ord('a')
        numericNewChar=(numericChar+key)% 26
        numbericNewChar=numericChar + ord('a')
        newChar=chr(numericNewChar)
        ct= ct + newChar
    return ct
还有一个问题我想让问题返回“bcdefg”,但它返回了“\x01\x02\x03\x04\x05\x06”我很困惑,请帮忙-谢谢

ceasarEncipher('abcdef',1)
应该是

currentChar = pt(i) #It is considering this as a function call. 
演示:

因为pt是一个字符串,这里:

>>> def ceasarEncipher(pt,key):
...     for i in range(0,len(pt)):
...         ct=""
...         currentChar=pt[i]
...         numericChar=ord(currentChar)-ord('a')
...         numericNewChar=(numericChar+key)% 26
...         numbericNewChar=numericChar + ord('a')
...         newChar=chr(numericNewChar)
...         ct= ct + newChar
...     return ct
... 
>>> ceasarEncipher('abcdef',1)
'\x06'
>>> 
您尝试将其作为函数调用,并传入参数i。请记住,添加。。。Python中的对象调用该对象之后

我想你真正想做的是用I索引pt。为此,您需要使用方括号:

currentChar=pt(i)
然而,几乎没有理由这样做:

currentChar=pt[i]
因为您可以通过以下方式更高效地完成相同的任务:


在上面的代码中,对于for循环的每次迭代,idx将是当前索引。

Python使用方括号索引字符串[]:


非常感谢,我认为我在方括号中犯了一个错误。还有一个问题我想让问题返回“bcdefg”,但返回“\x01\x02\x03\x04\x05\x06”我很困惑,请帮助
currentChar=pt[i]
for i in range(len(collection)):
    var = collection[i]
def ceasarEncipher(pt,key):
    for idx,_ in enumerate(pt):
        ct=""
        numericChar=ord(idx)-ord('a')
        numericNewChar=(numericChar+key)% 26
        numbericNewChar=numericChar + ord('a')
        newChar=chr(numericNewChar)
        # This is the same as `ct = ct + newChar`
        ct += newChar
    return ct
currentChar = pt[i]