osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

python 2 urlopen vs python 3 urlopen


On 8/27/2018 1:25 PM, Sean Darcy wrote:
> python 2 :
> 
> python
> Python 2.7.15 (default, May 15 2018, 15:37:31)
> .....
>>>> import urllib2
>>>> res = urllib2.urlopen('https://api.ipify.org').read()
>>>> print res
> www.xxx.yyy.zzz

In Python 2, this is the printed representation of a bytestring.

> python3
> 
> python3
> Python 3.6.6 (default, Jul 19 2018, 16:29:00)
> ...
>>>> from urllib.request import urlopen
>>>> res = urlopen('https://api.ipify.org').read()
>>>> print(res)
> b'ww.xxx.yyy.zzz'

In Python 3, this is the printed representation of the *same* bytestring.

> I'm expecting the python 2 result, just the ip address.

That is exactly what you got.

> How can I get
> python 3 just to give the address, and not include  b'      '  ?

These are not part of the bytestring, just how it is printed.

You need to read something about the switch from byte strings to unicode 
strings as the 'string' class.  But I don't know specifically what to 
recommend.

-- 
Terry Jan Reedy