[Tutor] unicode help (COM)

Kent Johnson kent37 at tds.net
Sun Dec 5 14:58:18 CET 2004


Rene Bourgoin wrote:
> Thanks for the responses. i'm a non-programmer and was learning/playing with some pyhton COM .
> 
> I'm trying to get my resluts from an excel spreadsheet to be saved or printed or stored as a python string. when i run this the results are in  unicode.....

What problem are the unicode strings causing? If you want to convert them to normal strings you can 
use the encode method:

 >>> s=u'abc'
 >>> s
u'abc'
 >>> s.encode('ascii')
'abc'

Now it's a plain string. If the unicode string includes characters that aren't available in the 
selected encoding you will get an error:

 >>> s=u'ä'
 >>> s.encode('ascii')
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 0: ordinal not in 
range(128)

You can change the handling of unknown characters by passing a second 'error' parameter:

 >>> s.encode('ascii', 'replace')
'?'

or pick a different encoding:

 >>> s.encode('utf-8')
'\xc3\xa4'

You can find a list of supported encodings in the docs for the 'codecs' module.

Kent

> 
> 
> from win32com.client import Dispatch
> xlApp = Dispatch("Excel.Application")
> xlApp.Visible = 0
> xlApp.Workbooks.Open("c:\sheet.xls")
> excelout = ()
> excelout = xlApp.ActiveSheet.Range("C4:D10").Value
> for item in excelout:
>    print item
> 
> _______________________________________________
> No banners. No pop-ups. No kidding.
> Make My Way your home on the Web - http://www.myway.com
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


More information about the Tutor mailing list