Ali
Ali

Reputation: 85

AttributeError: 'tuple' object has no attribute 'decode' while trying to decode string

I am running this code on Python 3. I encoded the data using .encode('utf_8') while accepting from the server. But now I want to decode it in order make it human readable.

 All1 = soup.findAll('tag_name', class_='class_name')
 All2 = "".join([p.text for p in All1])
 str = "1",All2.encode('utf_8')
 print(str.decode('utf_8')) 

But it is giving the following error:

print(str.decode('utf_8'))
    AttributeError: 'tuple' object has no attribute 'decode'

How can I decode it ?

Upvotes: 1

Views: 18944

Answers (2)

Francisco C
Francisco C

Reputation: 381

I run into this error frequently using SageMaker Pipelines. If you are in the same boat and are lost because the logs are not at all pointing you to what portion of code is causing AttributeError: 'tuple' object has no attribute 'decode', I can tell you that for me it always occurs because I have a dangling comma that I introduced at the end of some line of code (and my IDE did not complain about).

I've realized I induce this error whenever I am copying and pasting code or am refactoring.

For example

func(
    a=funcA(...),
    b=funcB(...),
)

gets refactored into

a=funcA(...),
b=funcB(...),
func(
    a=a,
    b=b,
)

where I have just copy pasted lines of code and kept problematic commas! Instead, remember to clean them up as

a=funcA(...)
b=funcB(...)
func(
    a=a,
    b=b,
)

Upvotes: 1

TigerhawkT3
TigerhawkT3

Reputation: 49318

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'))

Upvotes: 2

Related Questions