str (don't name your variables after built-in functions, by the way) is a tuple, not a string.

str = "1",All2.encode('utf_8')

This is equivalent to the more readable:

str = ("1", All2.encode('utf_8'))

I don't know what you need the "1" for, but you might try this:

num, my_string = '1', All2.encode('utf_8')

And then decode the string:

print(my_string.decode('utf_8'))
Answer from TigerhawkT3 on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › tuple' object has no attribute 'decode'
r/learnpython on Reddit: tuple' object has no attribute 'decode'
December 12, 2020 -

im trying to pass number and operator to the server and pass back the answer using a UDP socket.

i get a 'tuple' object has no attribute 'decode' . on line 20 of the client. (print(answer.decode()).

if i take out the decode and input 5 + 5 it returns (b'10', ('127.0.0.1', 12456)).

can anyone help ve no idea. only been doing this for a week haha! code below

thanks alot.

client-

from socket import *
import socket
serverName = 'Localhost'
serverPort = 12456
clientSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
number1 = input ('Input number1: ')
number2 = input ('Input number2: ')
operator = input ('Select an operator: (+ / * -) ')

clientSocket.sendto(number1.encode(),(serverName,serverPort))
clientSocket.sendto(number2.encode(),(serverName,serverPort))
clientSocket.sendto(operator.encode(),(serverName,serverPort))
answer= clientSocket.recvfrom(2048)
print (answer.decode())
clientSocket.close()

server -

from socket import *
import socket
serverName = 'Localhost'
serverPort = 12456
serverSocket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
serverSocket.bind(('',12456))
print ('The server is connected')
while 1:
number1, clientAddress = serverSocket.recvfrom(2048)
number2, clientAddress = serverSocket.recvfrom(2048)

operator, clientAddress = serverSocket.recvfrom(2048)

if str(operator) == '+':
answer = int(number1.decode()) + int(number2.decode())
answer = str(answer)
serverSocket.sendto(answer.encode(),clientAddress)
elif str(operator) == '-':
answer = int(number1.decode()) - int(number2.decode())
answer = str(answer)
serverSocket.sendto(answer.encode(),clientAddress)
elif str(operator) == '/':
answer = int(number1.decode()) / int(number2.decode())
answer = str(answer)
serverSocket.sendto(answer.encode(),clientAddress)
elif str(operator) == '*':
answer = int(number1.decode()) * int(number2.decode())
answer = str(answer)
serverSocket.sendto(answer.encode(),clientAddress)
serverSocket.close()

Top answer
1 of 3
2
Check the doc for what socket.recvfrom() returns. Which is a tuple containing the text and the replying address. If you want to decode the data received (which is inside the tuple) then you need to get it out of the tuple first. Something like: answer = clientSocket.recvfrom(2048) (data, address) = answer print(data.decode()) You'll probably need to specify the encoding, perhaps "utf-8".
2 of 3
1
hey thanks guys, i have it working now. ill paste the code. thanks for the help server ------ import socket sPort = 12000 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # creat socket object s.bind(('',sPort)) # bind with localhost(127.0.0.1) and socket print ('server is Ready') # print that the server is ready to recieve the data while 1: message, clientAddress = s.recvfrom(2048) # recieve data from client message2, clientAddress = s.recvfrom(2048) message3, clientAddress = s.recvfrom(2048) number1  = (message.decode()) # decode data from client and assign it to an var number2 = (message2.decode()) number3 = (message3.decode()) number4 = int(number3) if (number4 == 1) : # if, elif to select the operation from user depending on the input from client modMessage1 = int(number1) + int(number2) #change the string recieved into a int modMessage = str(modMessage1) # change the int answer back to a str s.sendto(modMessage.encode(), clientAddress) #encode the string and pass it back to client # each section does the same as the first depending on the client input. elif (number4 == 2 ) : modMessage1 = int(number1) - int(number2) modMessage = str(modMessage1) s.sendto(modMessage.encode(), clientAddress) elif (number4 == 3 ) : modMessage1 = int(number1) * int(number2) modMessage = str(modMessage1) s.sendto(modMessage.encode(), clientAddress) elif (number4== 4 ) : modMessage1 = int(number1) / int(number2) modMessage = str(modMessage1) s.sendto(modMessage.encode(), clientAddress) client ------ import socket serverIP = "localhost" sPort = 12000 cs = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # creat socket object message = input('numer1\r\n') # read in first number in sum message2 = input('numebr2\r\n') # read in second number in sum message3 = input('1 to add, 2 for subtract, 3 for multiply, 4 for divide \r\n') # read in waht math operation user would like to do # send data to server make sure to encode it... cs.sendto(message.encode(), (serverIP, sPort)) cs.sendto(message2.encode(), (serverIP, sPort)) cs.sendto(message3.encode(), (serverIP, sPort)) # recieve modifed data from server and print it to terminal modMessgae = cs.recv(2048) print (modMessgae.decode()) # closesocket cs.close()
Discussions

Python AttributeError: 'tuple' object has no attribute 'encode' in hashlib.encode - Stack Overflow
When the interpreter shows "'tuple' object has no attribute 'encode' means that the object tuple does not support convert that way. More on stackoverflow.com
🌐 stackoverflow.com
duplicity suddenly fails with Python tuple error - Unix & Linux Stack Exchange
I have been using duplicity in a cron job for a year now, has worked just fine. Starting from last week I got the following message: Ausdruckbasierte Dateiliste wird gelesen /home/mu/.config/exclu... More on unix.stackexchange.com
🌐 unix.stackexchange.com
August 17, 2019
python - How to solve the error: 'tuple' object has no attribute 'decode' with django-channels - Stack Overflow
When I tried to execute the channels' tutorial in order to establishing the django website with websocket, the error message emerged: AttributeError: 'tuple' object has no attribute 'decode' I just More on stackoverflow.com
🌐 stackoverflow.com
AttributeError: 'tuple' object has no attribute 'encode'

You should provide the full trace back. We aren't mind readers.

More on reddit.com
🌐 r/django
5
1
August 13, 2020
🌐
GitHub
github.com › django › channels_redis › issues › 334
AttributeError: 'tuple' object has no attribute 'decode' when configuring using tuples · Issue #334 · django/channels_redis
October 21, 2022 - File "[..]lib/python3.10/site-... "/usr/lib/python3.10/urllib/parse.py", line 112, in <genexpr> return tuple(x.decode(encoding, errors) if x else '' for x in args) AttributeError: 'tuple' object has no attribute 'decode'...
Author   vanschelven
🌐
Narkive
comp.lang.python.narkive.com › hROupzov › attributeerror-tuple-object-has-no-attribute-encode
AttributeError: 'tuple' object has no attribute 'encode'
Post by erikcw It raises this error: AttributeError: 'tuple' object has no attribute 'encode' What does? I imagine that this error comes from a call to a cursor object's execute method. In other words, I imagine that you may be cursor.execute(*sql) Not that there would be anything obviously wrong with that: you are keeping the string and its parameters separate, after all.
🌐
LearnDataSci
learndatasci.com › solutions › python-attributeerror-tuple-object-has-no-attribute
Python AttributeError: 'tuple' object has no attribute – LearnDataSci
The underscore conveys to readers of your code that you intend not to use the index value. The error AttributeError: 'tuple' object has no attribute is caused when treating the values within a tuple as named attributes.
🌐
Stack Overflow
stackoverflow.com › questions › 74665490 › how-to-solve-the-error-tuple-object-has-no-attribute-decode-with-django-cha
python - How to solve the error: 'tuple' object has no attribute 'decode' with django-channels - Stack Overflow
I think the problem may caused by asgiref, but there is no documentation for reference. ... I think async_to_sync requires a function input instead of a tuple. Hopefully this works.
Find elsewhere
🌐
Reddit
reddit.com › r/django › attributeerror: 'tuple' object has no attribute 'encode'
r/django on Reddit: AttributeError: 'tuple' object has no attribute 'encode'
August 13, 2020 -

I am creating a Contact page for my django project. forms.py has name, subject, sender and message. Here's the view:

And the form:

<form method="POST">

{%csrf_token%}

{{form.as_p}}

<button type="submit">Send</button>

</form>

After I click Send I get this error: AttributeError: 'tuple' object has no attribute 'encode' and I can't seem to figure out what's wrong despite checking other questions of the same type.

I am using google SMTP server, from this link following its instructions.

🌐
Python Forum
python-forum.io › thread-12795.html
Getting decode error.
import sys import os import subprocess import inspect def run_process(cmd_args): with subprocess.Popen(cmd_args) as p: p.communicate() if __name__ == "__main__": f = open(os.environ, 'w') cmd_args_cnt
🌐
Bytes
bytes.com › home › forum › topic › python
AttributeError: 'tuple' object has no attribute 'encode' - Post.Byes
May 4, 2007 - It raises this error: AttributeError: 'tuple' object has no attribute 'encode' > What does? I imagine that this error comes from a call to a cursor object's execute method.
🌐
Reddit
reddit.com › r/learnpython › 'tuple' object has no attribute 'encode' for stmplib, two variables into one variable?
r/learnpython on Reddit: 'tuple' object has no attribute 'encode' for stmplib, two variables into one variable?
April 29, 2022 -

I am trying to call the function send_email with the variable message in it and combining it with a string contained in AlertSMSText and assigning it to text as well as html to HTMLEmailBody.

For some reason when I do text = AlertSMSText, message and it gives me the error AttributeError: 'tuple' object has no attribute 'encode' but if I do text = AlertSMSText + message and html = HTMLEmailBody + message it works fine except it ignores \n contained in the string that AlertSMSText has in it.

SendEmailAlert.py

def send_email(message):
  email_subject = JSONFileReader.SubjectEmail  
  sender_add = JSONFileReader.SenderEmail  
  receiver_add = JSONFileReader.ReceiverEmail  
  smsEmail_add = JSONFileReader.SMSEmailAdd  # SMS email
  AlertSMSText = JSONFileReader.AlertSMSText #Alert SMS Text message
  HTMLEmailBody = JSONFileReader.AlertHTMLEmailBody  #Alert Email message in HTML format
  password = JSONFileReader.gmailPass  # Password for the email you're sending from

  # Below is creating the SMTP server object by giving the SMPT server an address and port number
  smtp_server = smtplib.SMTP("smtp.gmail.com", 587)
  smtp_server.ehlo()  # setting the ESMTP protocol
  smtp_server.starttls()  # setting up to TLS connection
  smtp_server.ehlo()  # calling the ehlo() again as encryption happens on calling startttls()
  smtp_server.login(sender_add, password)  # logging into the senders email

  rcpt = smsEmail_add.split(",") + [receiver_add]  # Formats the recipients emails
  # Create message container - the correct MIME type is multipart/alternative.
  msg = MIMEMultipart('alternative')
  msg['Subject'] = email_subject
  msg['From'] = sender_add
  msg['To'] = receiver_add
  msg['Cc'] = smsEmail_add

  message.encode('utf-8')

  # Create the body of the message (a plain-text is for SMS and HTML is for email)
  text = AlertSMSText, message
  html = HTMLEmailBody, message


  # Record the MIME types of both parts - text/plain and text/html.
  part1 = MIMEText(text, 'plain')
  part2 = MIMEText(html, 'html')

  # Attach parts into message container.
  # According to RFC 2046, the last part of a multipart message, in this case
  # the HTML message, is best and preferred.
  msg.attach(part1)
  msg.attach(part2)

  smtp_server.sendmail(sender_add, rcpt, msg.as_string()) #Sends the email

  smtp_server.quit()  #Terminates the SMTP server

 ip= "10.1.50.2"
 send_email(ip + " is down.\n\nPlease reply with 'Ack' to pause alerts for 60 minutes")

In the JSON, the AlertSMSTextvariable equals to "Alert SMS Text": "This is an alert for your services \n\n IP: "

The output when text = AlertSMSText + message is all on one line and ignores newline \n:

This is an alert for your services IP:10.1.50.0 is down. Please reply with 'Ack' to pause alerts for 60 minutes

I want it to be:

This is an alert for your services

IP:10.1.50.0 is down. 

Please reply with 'Ack' to pause alerts for 60 minutes
🌐
The Coding Forums
thecodingforums.com › archive › archive › python
AttributeError: 'tuple' object has no attribute 'encode' | Python | Coding Forums
April 5, 2007 - It may not display this or other websites correctly. You should upgrade or use an alternative browser. ... Hi, I'm trying to build a SQL string sql = """INSERT INTO ag ('cid', 'ag', 'test') VALUES(%i, %s, %d)""", (cid, ag, self.data[parent][child]['results']['test']) It raises this error: AttributeError: 'tuple' object has no attribute 'encode' Some of the variables are unicode (test and ag) - is that what is causing this error?
🌐
Free Python Source Code
freepythonsourcecode.com › post › 117
With Examples Fix attributeerror: 'tuple' object has no attribute ...
September 29, 2024 - The AttributeError: 'tuple' object has no attribute, which occurs when accessing an attribute or method that doesn't exist for a tuple object in Python.