Python:AttributeError:'int'对象没有属性'isalpha'

问题描述 投票:0回答:1

我想使用客户端/服务器在python中创建一个Caesar的密码函数。客户端发送带有密钥的消息,服务器对其进行加密。服务器代码:

import socket

def getCaesar(message, key):
    result=""
    for l in message:
        if l.isalpha():
            num = ord(l)
            num += key

            if l.isupper():
                if num > ord('Z'):
                    num -= 26
                elif num < ord('A'):
                    num += 26

            elif l.islower():
                if num > ord('z'):
                    num -= 26
                elif num < ord('a'):
                    num += 26

            result += chr(num)
        else:
            result += l
return result    

serverSock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host=socket.gethostname()
port=4000

serverSock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

serverSock.bind((host,port))
serverSock.listen(5)
print("Listenting for requests")
while True:
    s,addr=serverSock.accept()
    print("Got connection from ",addr)
    print("Receiving...")

    message=s.recv(1024)
    key=s.recv(1024)

    resp=getCaesar(message, key)
    print('Ciphertext: ')
    print(resp)

serverSock.close()

不断调用的行是第6行:'if l isalpha():'并给出错误:AttributeError:'int'对象没有属性'isalpha'。这个错误是什么意思?

客户计划:

import socket

def getMessage():
    print('Enter your message:')
    return input()

def getKey():
    key = 0
    while True:
        print('Enter the key number (1-%s)' % (26))
        key = int(input())
        if (key >= 1 and key <= 26):
            return key

s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host=socket.gethostname()
port=4000
s.connect((host,port))


message = getMessage()
key = getKey()

message=message.encode()


s.send(message)
s.send(bytes(key))
cipher= s.recv(1024)

print('Ciphertext: ')
print(cipher)
s.close()
python client-server caesar-cipher
1个回答
3
投票

在python 3中,socket recv返回一个不可变的bytes序列。每个元素的类型为int,其范围为[0,255]。 isalphastr的一种方法,并不是int的方法。

如果您希望将服务器响应视为字符串,则可以解码字节。

string = response.decode('utf-8')

for c in string:
    if c.isalpha():
        [...]
© www.soinside.com 2019 - 2024. All rights reserved.