1

Right now, I'm coding a python SMTP script.

status = clientSocket.recv(1024)
print (status)

When python prints status, I get:

b'250-mx.google.com at your service, [107.216.175.252]\r\n250-SIZE 35882577\r\n250-8BITMIME\r\n250-AUTH LOGIN PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKEN\r\n250-ENHANCEDSTATUSCODES\r\n250 CHUNKING\r\n'

However, I want python to turn \r\n into the actual new lines and not just print it out as one giant line. How would I go about doing this?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
user2837858
  • 339
  • 6
  • 18

2 Answers2

3

status has bytes type, so you need to decode it to string.

2 obvious ways to achieve this:

  1. print(status.decode())
  2. print(str(status, 'utf-8'))

The default encoding for .decode is UTF-8, so if you want to use a different one, do status.decode(encoding). And status.decode(encoding) is exact equivalent to str(status, encoding).

Why just str(status) isn't working:

From the documentation on str function:

Passing a bytes object to str() without the encoding or errors arguments falls under the first case of returning the informal string representation. For example:

>>> str(b'Zoot!')
"b'Zoot!'"
vaultah
  • 44,105
  • 12
  • 114
  • 143
2
>>> print(status.decode())
250-mx.google.com at your service, [107.216.175.252]
250-SIZE 35882577
250-8BITMIME
250-AUTH LOGIN PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKEN
250-ENHANCEDSTATUSCODES
250 CHUNKING

You're on Python 3 which defaults to unicode, but you have an old style byte-string from doing sockets. You just have to decode it and then the print will get rid of newline representations as usual.

Two-Bit Alchemist
  • 17,966
  • 6
  • 47
  • 82
  • What is "old style" about byte strings? They have their use, and they'll always have their use. – glglgl Apr 12 '14 at 07:08
  • The fact that they were the default in Python 2 and no longer are in Python 3. Counter-question: what about being old implies being useless? (I still use "tar", the "**tape archiver**" every day. It's 30 years old and still works just fine.) – Two-Bit Alchemist Apr 12 '14 at 16:40