将str附加到s上

2024-10-02 10:25:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在用python做一个简单的Caesar转换,但是当我试着运行它时,它说:

File "Ceaser Shift.py", line 36, in main
ciphertext += shift(letter,shift)
TypeError: 'str' object is not callable

我试图弄清楚它为什么会这样做,我可以在正常的空闲环境中添加到字符串中,但没有看到任何联机的相关内容,因为我没有在脚本的任何地方重新定义str。 任何帮助都太好了!你知道吗

我的代码:

## Doesn't support changing shifts during computation, to do this either the database must be re-written or script restarted

import time, os, string

global selmemo
shiftmemo = {}

def shift(l,shift):
    if l not in shiftmemo:
        charset = list(string.ascii_lowercase)
        place = charset.index(l.lower())
        shiftplace = charset.index(shift.lower())

        shiftmemo[l] = charset[(place+shiftplace)%25]

    return shiftmemo[l]

def main():
    shift = None
    ciphertext = ""

    print("--- Welcome ---")
    print("--- Ceaser Shifter ---")
    print("Commands: shift, encrypt, clear, print, quit")
    choice = input(": ")

    while choice != "quit":
        if choice == "shift":
            shift = input("Please enter a shift letter: ")

        elif choice == "encrypt" and shift != None:
            uparse = input("Enter your plaintext: ")
            for letter in uparse:
                if letter.lower() in string.ascii_lowercase:
                    ciphertext += shift(letter,shift)
                else:
                    ciphertext += letter

        elif choice == "clear":
            shift = ""
            ciphertext = ""
            shiftmemo = {}

        elif choice == "print":
            print(ciphertext)

        else:
            pass

        choice = input(": ")

main()

Tags: ininputstringifshiftmainlowerprint
2条回答

shift只是一个名字。解释器将名称的值识别为用户定义的函数。因此,您可以通过将值赋给另一个名称来使用这样的函数:

>>> def func():
...     print('a')
... 
>>> f = func
>>> f()
a
>>> 

但是,如果您为名称指定了一个新值,则它可能不再是函数。你知道吗

>>> func = None
>>> type(func)
<class 'NoneType'>
>>> func()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable
>>> 

问题是您定义了函数shift和字符串变量shift。你知道吗

一个快速解决方法是重命名函数和变量,这样就不会有冲突。你知道吗

相关问题 更多 >

    热门问题