When appending a python variable to a list I am getting object values
Question:
print("Device discovered: %s" % remote)
m.append(remote)
print(m)
I am getting the following result. How Can I get same value is the list names m
Device discovered: 0013A20041481642 - REMOTE
[<digi.xbee.devices.RemoteZigBeeDevice object at 0x7f42c312ceb8>]
Answers:
Did you try m.append(str(remote))
? It is possible there is a __str__
function implemented in remote
object. Such magic function will handle object to string conversion when it’s necessary. When you format the object it is necessary to convert to str but when you append it to a list it’s not.
List contents use the repr()
result of the objects contained, which in turn uses the __repr__
method on an object.
print()
converts objects with str()
, which will use a __str__
method, if present, __repr__
otherwise.
You remote
object (a digi.xbee.devices.RemoteZigBeeDevice
instance) only has a __str__
method, and no __repr__
method. Implement the latter to customise how your object is shown in a list.
Alternatively, print all individual values in the list with:
print(*m)
These are then space separated, use sep='...'
to specify a different separator.
Or you could convert all the objects in the list to a string before printing:
print([str(obj) for obj in m])
and print the list of strings.
print("Device discovered: %s" % remote)
m.append(remote)
print(m)
I am getting the following result. How Can I get same value is the list names m
Device discovered: 0013A20041481642 - REMOTE
[<digi.xbee.devices.RemoteZigBeeDevice object at 0x7f42c312ceb8>]
Did you try m.append(str(remote))
? It is possible there is a __str__
function implemented in remote
object. Such magic function will handle object to string conversion when it’s necessary. When you format the object it is necessary to convert to str but when you append it to a list it’s not.
List contents use the repr()
result of the objects contained, which in turn uses the __repr__
method on an object.
print()
converts objects with str()
, which will use a __str__
method, if present, __repr__
otherwise.
You remote
object (a digi.xbee.devices.RemoteZigBeeDevice
instance) only has a __str__
method, and no __repr__
method. Implement the latter to customise how your object is shown in a list.
Alternatively, print all individual values in the list with:
print(*m)
These are then space separated, use sep='...'
to specify a different separator.
Or you could convert all the objects in the list to a string before printing:
print([str(obj) for obj in m])
and print the list of strings.