user1765661
user1765661

Reputation: 595

Python - print 'object' information

I have a variable that is outputing this when I do a simple for loop:

for filex in variable:

    print filex

# OUTPUT #

'proj1' (objectName 0x2267c4f0)
'proj2' (objectName 0x2267a770)
'proj3' (objectName 0x22679690)
'proj4' (objectName 0x2267d0d0)

# OUTPUT #

I Want to extract just the text between quotes like 'proj1'. But I get this error when using indexing:

for filex in variable:

    print filex[0]

# OUTPUT #

  File "<string>", line 11, in <module>
TypeError: 'objectName' object does not support indexing

# OUTPUT #

*I am using python inside an host application.

Upvotes: 0

Views: 345

Answers (2)

Santa
Santa

Reputation: 11547

Seems like filex is an object of a custom class that does not implement __getitem__ method.

When you do:

filex[0]

What actually is invoked is:

filex.__getitem__(0)

The output string "'proj1' (objectName 0x2267c4f0)" is likely the returned value from filex.__str__ or filex.__repr__.

If so, the 'proj1' string you're looking for might be accessible from one of filex's other attributes or methods associated with them.

Barring that, you can hack your way by parsing the returned value of repr(filex), but that's not really robust, IMO.

Upvotes: 2

bakkal
bakkal

Reputation: 55448

I suggest you find out the name of that attribute you want, e.g. if it was name, then you can access it directly with filex.name where 'proj1' is stored

If you don't know what that attribute is, you can use dir(filex) to see all the attributes

Upvotes: 1

Related Questions