Printing HTML data with Python 3
<p>I am new to Python. I am doing a course in Python 2.7, but at the same time, I want to be able to do everything in Python 3.</p>

<p>Code in Python 2.7:</p>

<pre><code>import socket

mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('www.py4inf.com', 80))
mysock.send('GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n')

while True:
    data = mysock.recv(512)
    if ( len(data) &lt; 1 ) :
        break
    print data

mysock.close()
</code></pre>

<p>Yields properly formatted data, like so:</p>

<pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt;
</code></pre>

<p>Code in Python 3:</p>

<pre><code>import socket

mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('www.py4inf.com', 80))
mysock.send(('GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n').encode())

while True:
    data = mysock.recv(512)
    if ( len(data) &lt; 1 ) :
        break
    print(data);

mysock.close()
</code></pre>

<p>And it yields:</p>

<pre><code>b'HTTP/1.1 200 OK\r\nContent-Type: text/html; charset="utf-8"\r\nContent-Length: 2788\r\nConnection: Close\r\n\r\n&lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"&gt;\n&lt;html&gt;\n&lt;head&gt;\n&lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt;\n 
</code></pre>

<p>As you can see, it adds a "b" character, and ignores \r \n. The formatting is way off.
Where did the 'b' come from? How can I make python format it properly?
I have tried converting it to a string, prior to printing but it didn't help.</p>

<p>It has a <code>b''</code> because what is returned by <code>mysock.recv</code> is of type <code>bytes</code>. You should decode your byte string to a unicode one with <code>decode</code>:</p>

<pre><code>print(data.decode('utf-8'))
</code></pre>

<p>Remember, Python 2 and 3 differ regarding strings as specified in <a href="https://www.python.org/dev/peps/pep-3137/" rel="nofollow"><code>PEP 3137</code></a>. Python 3 offers a clear separation between text and binary data, Python 2 doesn't.</p>

<p>The issue here is that when <code>print</code> receives your bytes object, it'll call <code>str</code> on it which will simply build a string out of it as it knows best; i.e escape backslashes and retain the rest:</p>

<pre><code>&gt;&gt;&gt; str(b"hello\nworld")
"b'hello\\nworld'"
</code></pre>

<p>Then <code>print</code> will just take that and print it out.</p>

python python-2.7 python-3.x