Python 如何获取对象的Unicode表示形式

Python 如何获取对象的Unicode表示形式,python,unicode,com,Python,Unicode,Com,我有一个实例,我想得到它的Unicode表示。Unicode函数Unicode()只接受字符串或缓冲区,因此如果直接传递实例,就会出现错误 我试过这个: document = self.grammar.application.ActiveDocument style_map = [( unicode(s, 'utf-8'), s) for s in document.Styles] self.styles.set(dict(style_map)) 我得到这个错误: style_map = [

我有一个实例,我想得到它的Unicode表示。Unicode函数Unicode()只接受字符串或缓冲区,因此如果直接传递实例,就会出现错误

我试过这个:

document = self.grammar.application.ActiveDocument
style_map = [( unicode(s, 'utf-8'), s) for s in  document.Styles]
self.styles.set(dict(style_map))
我得到这个错误:

style_map = [( unicode(s, 'utf-8'), s) for s in  document.Styles]
TypeError: coercing to Unicode: need string or buffer, instance found
我想知道如何将这些实例转换为Unicode字符串表示。 我没有实现这些对象。我通过COM接口访问它们

背景:

这是通过COM接口使用Python访问Word文档中可用格式样式的代码。 如果我只是尝试将对象转换为ASCII字符串,则会出现以下错误:

style_map = [( unicode(s), s) for s in  document.Styles]
File "C:\Python26\lib\site-packages\win32com\client\dynamic.py", line 207, in __str__ return str(self.__call__())
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf3' in position 3: ordinal not in range(128)
我宁愿在我的代码中处理这个问题,而不是修改一些Win32代码。
如您所见,我正在使用Python 2.6。

尝试使用
repr()将实例转换为表示形式。


好吧,我没有得到任何错误,但是我不认为这是正确的。生成的列表包含COM对象的名称。因此,我有一个重复多次使用此字符串的列表:u“”。我应该有一个带有样式名称的列表。:SWith
repr
您可以得到手头对象的字符串表示:
repr('a')
gives
“'a'”
repr(sys)
gives
”。在许多情况下,它与
str
相同。一个值得注意的例外是字符串
str('A')
给出
'A'
。提示:如果你认为某个答案有用,你可以投票表决检查
dir(s)
这种样式提供了哪些属性,并使用其中一种,希望更多的描述性属性,如
name
title
等,然后将其转换为unicode。顺便说一句,您的问题是“如何获得对象的unicode表示”。这正是我的答案。想要一个有说服力的名字是另一个问题
document = self.grammar.application.ActiveDocument
style_map = [( unicode(repr(s), 'utf-8'), s) for s in document.Styles]
self.styles.set(dict(style_map))