【问题标题】:Getting TypeError: 'str' object is not callable in my script获取 TypeError:'str' 对象在我的脚本中不可调用
【发布时间】:2021-08-06 18:45:56
【问题描述】:

运行此程序时,我收到错误“TypeError:'str' object is not callable”。有什么想法吗?

def caesar_encrypt(text,num):
    i = ""

    for i in text:
        if not i.isalpha():
            i += i
        elif i.isupper():
            i += i(((ord(i) + num - 65) %26) + 65)
        else:
            i += i(((ord(i) + num - 97) %26) + 97)
    return i

s=input("please enter the message: ")
step=int(input("now enter the step "))

encrypted_msg=caesar_encrypt(s, num)
print(encrypted_msg)

【问题讨论】:

  • encrypted_msg=caesar_encrypt(s, num) -> encrypted_msg=caesar_encrypt(s, step)
  • 欢迎来到 SO! i( ... bunch of other stuff ... ) 应该如何工作?错误很明显:您正在调用像"x"() 这样的字符串,它最低限度地重现了问题。 i 是一个字符串。看起来你有一个变量别名问题,循环变量覆盖了外部i。仅将 i 用于整数和索引,而不用于字符串或元素。你想完成什么?
  • 总是将完整的错误消息(从单词“Traceback”开始)作为文本(不是截图,不是链接到外部门户)有问题(不是评论)。还有其他有用的信息。
  • 我认为您应该简单地删除 ii += i(...)() 之前的 i += i(...)
  • 您是否也必须能够解码编码字符串?

标签: python string


【解决方案1】:

发布的代码存在一些问题。首先,对caesar_encrpyt() 的调用需要看起来像caesar_encrypt(s, step)。其次,该函数中有两个局部变量,定义为i;应将返回的那个更改为更具描述性的名称。最后,导致您的错误的原因是i += i(((ord(i) + num - 97) %26) + 97)i += i(((ord(i) + num - 65) %26) + 65)。这里i 是一个字符串,正如错误所暗示的那样,它是不可调用的;相反,这应该调用chr() 将结果转换回字符。

这是固定代码的样子: `

def caesar_encrypt(text,num):
    encoded_msg = ""

    for i in text:
        if not i.isalpha():
            encoded_msg += i
        elif i.isupper():
            encoded_msg += chr(((ord(i) + num - 65) %26) + 65)
        else:
            encoded_msg += chr(((ord(i) + num - 97) %26) + 97)
    return encoded_msg

s=input("please enter the message: ")
step=int(input("now enter the step "))

encrypted_msg=caesar_encrypt(s, step)
print(encrypted_msg)

`

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-27
    • 2015-03-07
    • 2019-03-05
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多