'Python: AttributeError: 'int' object has no attribute 'isalpha'
I'm looking to create a Caesar's Cipher function in python using client/server. The client sends a message with a key and the server encrypts it. Server Code:
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()
The line that keeps getting called out is line 6:' if l isalpha(): ' and gives me the error: AttributeError: 'int' object has no attribute 'isalpha'. What does this error mean?
Client Program:
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()
Solution 1:[1]
In python 3, socket recv
returns an immutable sequence of bytes
. Each element has type int
and is in the range [0, 255]. isalpha
is a method of str
and is not a method of int
.
If you'd like to treat the server response as a string, you can decode the bytes.
string = response.decode('utf-8')
for c in string:
if c.isalpha():
[...]
Solution 2:[2]
as mentioned in above answer, isalpha()
is the method of string so apply explicit string casting for object l,
Instead of l.isalpha()
use this str(l).isalpha()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Sanketkumar7 |