Python Forum
TypeError: initial_value must be str or None, not bytes
Thread Rating:
  • 1 Vote(s) - 4 Average
  • 1
  • 2
  • 3
  • 4
  • 5
TypeError: initial_value must be str or None, not bytes
#1
Hi all

Here is a snapshot of my code:

for num in data[0].split():
    typ, data = mail.fetch(num,'(RFC822)')


    for response_part in data:
        if isinstance(response_part, tuple):
            msg = email.message_from_string(response_part[1])
Error comes from:
msg = email.message_from_string(response_part[1])
Error message:
TypeError: initial_value must be str or None, not bytes
Have been looking at google for an hour now, and Ive tried playing around with the is.BytesIO and StringIO but I just cant get it working. The problem seems to have something to do with the difference between Python 2 and 3.

Kind Regards,
Peter

I tried:

msg = io.StringIO(email.message_from_string(response_part[1]))
Doesn't help

Br, Peter
Reply
#2
Try:
msg = email.message_from_string(response_part[1].decode())
Everything that comes in from outside into Python 3 most have a encoding so it will be Unicode,
if not it will be bytes.
That's because Python 3 has full Unicode support and will not mix stuff together in a string like Python 2 did.
>>> s = b'hello'
>>> type(s)
<class 'bytes'>

# Convert to string(which is Unicode bye default Python 3)
>>> s.decode()
'hello'
>>> # Same as 
>>> s.decode('utf-8')
'hello'
>>> type(s.decode())
<class 'str'>
Reply
#3
Brilliant it works as a charm..

Many thanks!
Br, Peter
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  TypeError: a bytes-like object is required ZeroX 13 4,172 Jan-07-2023, 07:02 PM
Last Post: deanhystad
  TypeError: a bytes-like object is required, not 'str' - Help Please. IanJ 3 4,824 Aug-29-2022, 05:53 PM
Last Post: deanhystad
  python 3: TypeError: a bytes-like object is required, not 'str' wardancer84 3 6,518 Jul-09-2021, 05:55 PM
Last Post: deanhystad
  TypeError: int() argument must be a string, a bytes-like object or a number, not 'Non Anldra12 2 5,220 May-02-2021, 03:45 PM
Last Post: Anldra12
  TypeError: a bytes-like object is required, not 'str' ozzy69 1 2,862 Jul-17-2020, 03:38 PM
Last Post: stullis
  Packet Sniffer - TypeError: a bytes-like object is required, not 'str' cheffa2020 4 5,325 Jun-12-2020, 02:10 PM
Last Post: cheffa2020
  Why, TypeError: expected string or bytes-like object ? JohnnyCoffee 3 18,631 May-08-2020, 04:26 AM
Last Post: bowlofred
  TypeError: a bytes-like object is required, not 'str'. jacklee26 4 5,664 Apr-18-2020, 11:04 PM
Last Post: jacklee26
  replace bytes with other byte or bytes BigOldArt 1 10,643 Feb-02-2019, 11:00 PM
Last Post: snippsat
  builtins.TypeError: a bytes-like object is required, not 'str' BigOldArt 0 3,996 Jan-31-2019, 10:46 PM
Last Post: BigOldArt

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020