Byte-Array to String

Carsten Haese carsten at
Fri Apr 20 15:00:08 CEST 2007

On Fri, 2007-04-20 at 09:51 +0100, Robert Rawlins - Think Blue wrote:
> Morning Steve,
> That stuff looks mighty promising, I did play around with the
> toString() function yesterday but couldn’t get the damned thing
> working.

That's because Steven seems to have given you suboptimal advice. The
thing you're working with is a dbus.Array of dbus.Byte, not a Python
array, so Python's standard array module is not going to help you.

When you work with an API function and you don't know what to do with
the results of calling that function, the documentation for that API
should be your first place to look for help. I don't know what you're
referencing, but Google tells me that the python-dbus API is documented

So, what do you do with a dbus.Array full of instances of dbus.Byte?
Let's look at their documentation,

The page about dbus.Array tells us that it inherits from list, so you
should be able to do indexed access into it and iterate over it.
dbus.Byte inherits from int, and the documentation says that a dbus.Byte
can be converted to a character (string of length 1) by calling str or
chr on it.

So, to get a string from your dbus.Array, you could do something like

s = ""
for b in myDbusArray:
  s += chr(b)

However, it's better (faster) to use the join idiom for building a
string char-by-char:

s = "".join(chr(b) for b in myDbusArray)

That ought to give you the string you're asking for.



More information about the Python-list mailing list