简体   繁体   English

将str附加到str

[英]Appending str onto str

I've been working on a simple Caesar Shift in python, but when I try to run it it says that: 我一直在用python开发一个简单的Caesar Shift,但是当我尝试运行它时,它说:

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

I've tried to figure out why it does this, and I can add to a string in the normal IDLE environment and haven't seen anything online relatable because I haven't redefined str anywhere in my script. 我试图弄清楚为什么这样做,并且我可以在正常的IDLE环境中添加到字符串,并且没有看到任何可在线关联的内容,因为我没有在脚本的任何地方重新定义str。 Any help would be great! 任何帮助将是巨大的!

My Code: 我的代码:

## 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()

The problem is that you defined your function shift and your string variable shift . 问题是您定义了函数shift和字符串变量shift

A quick fix is to rename your functions and variables so that there is no conflict. 一种快速解决方案是重命名函数和变量,以免发生冲突。

The shift is just name. shift只是名字。 It is the value of the name that is recognized as a user-defined function by the interpreter. 它是解释器识别为用户定义函数的名称值。 So you can use function like this by assign the value to another name: 因此,可以通过将值分配给另一个名称来使用这样的功能:

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

But also if you assign a new value to the name, it may not be a function again. 而且,如果您给名称分配了新值,则它可能不再是一个函数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM