[Python-3000] PEP 3138- String representation in Python 3000

M.-A. Lemburg mal at egenix.com
Wed May 14 20:51:22 CEST 2008


On 2008-05-14 19:43, Martin v. Löwis wrote:
>> Hardwiring the encoding is not a good idea, esp. since there
>> are lots of alternatives for you to get readable output from
>> PyUnicode object now and without any changes to the interpreter.
>>
>> E.g.
>>
>> print '%s' % u.encode('utf-8')
> 
> We are talking about Python 3 here, so it is fairly important
> that you consider all syntactic and semantic details of Python
> 3 - otherwise it is not clear whether or not you are aware of
> them:
> - the print syntax is incorrect
> - .encode returns a byte string
> - therefore, %s applies __str__ to the byte string, yielding
>   something like b'...', with hex escapes for the non-ASCII
>   bytes

Sorry, I was in Python 2 mode.

For Python 3 you don't need the .encode() calls since the
stream will take care of that for you:

# Let sys.stdout take care of the encoding
print('"%s"' % u.transform('unicode-printable'))

# Log to a file:
logfile = open('my.log', 'a', encoding='unicode-printable')
logfile.write('"%s"' % u)

# Using a helper
def unicode_repr(u):
     return '"' + u.transform('unicode-printable') + '"'
print(unicode_repr(u))

For the purists: the above assumes that 'unicode-printable'
will encode '"' to '\"'.


BTW: I found that

   logfile = open('my.log', 'a', encoding='unicode-printable')

doesn't raise an exception. Only when you call the .write()
method you get the expected:

   LookupError: unknown encoding: unicode-printable

Is that intended ? IMO, such errors should not be deferred.

>> There are many ways to solve your problem.
> 
> No. If you strike out those that don't actually work, close
> to none remain.

They may look a bit different, but the logic is essentially
the same.

-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, May 14 2008)
 >>> Python/Zope Consulting and Support ...        http://www.egenix.com/
 >>> mxODBC.Zope.Database.Adapter ...             http://zope.egenix.com/
 >>> mxODBC, mxDateTime, mxTextTools ...        http://python.egenix.com/
________________________________________________________________________

:::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! ::::


    eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
     D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
            Registered at Amtsgericht Duesseldorf: HRB 46611


More information about the Python-3000 mailing list