Skip to content

Instantly share code, notes, and snippets.

@ssbarnea
Created June 26, 2011 11:51

Revisions

  1. ssbarnea revised this gist Jun 27, 2011. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion py27-str-unicode-bytes.py
    Original file line number Diff line number Diff line change
    @@ -1,7 +1,7 @@
    #! /usr/bin/env python

    """
    This code works with Python 2.6 but fails on Python 2.7
    """

    import httplib, urllib2
  2. ssbarnea revised this gist Jun 27, 2011. 1 changed file with 7 additions and 12 deletions.
    19 changes: 7 additions & 12 deletions py27-str-unicode-bytes.py
    Original file line number Diff line number Diff line change
    @@ -1,17 +1,12 @@
    #! /usr/bin/env python
    # -*- coding: utf-8 -*-

    import io, sys
    """
    unicode_str = u"" # u"" for py2

    some_bytes = b'\x40\x00\x01\x02\xFF'
    """

    a = io.BytesIO()
    a.write(some_bytes)
    import httplib, urllib2
    params = b'\x40\x00\x01\x02\xFF'

    b = a.getvalue()
    print("type(b)=%s" % type(b))

    if isinstance(b, str): # basestr on py2
    unicode_str += b # this line will throw UnicodeDecodeError on Python 2.7
    url = unicode("http://posttestserver.com/post.php")
    req = urllib2.Request(url, data=params)
    urllib2.urlopen(req)
  3. ssbarnea revised this gist Jun 26, 2011. 1 changed file with 3 additions and 0 deletions.
    3 changes: 3 additions & 0 deletions py27-str-unicode-bytes.py
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,6 @@
    #! /usr/bin/env python
    # -*- coding: utf-8 -*-

    import io, sys

    unicode_str = u"" # u"" for py2
  4. ssbarnea created this gist Jun 26, 2011.
    14 changes: 14 additions & 0 deletions py27-str-unicode-bytes.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,14 @@
    import io, sys

    unicode_str = u"" # u"" for py2

    some_bytes = b'\x40\x00\x01\x02\xFF'

    a = io.BytesIO()
    a.write(some_bytes)

    b = a.getvalue()
    print("type(b)=%s" % type(b))

    if isinstance(b, str): # basestr on py2
    unicode_str += b # this line will throw UnicodeDecodeError on Python 2.7