converting an array of chars to a string

Bengt Richter bokr at oz.net
Fri Jun 21 12:09:37 EDT 2002


On Fri, 21 Jun 2002 10:10:01 +0200, JB <jblazi at hotmail.com> wrote:

>How can I convert an array of chars to string?
>
Depends on what you mean by "an array of chars."

>The problem is this: I should like to perform 8 bit 
>calculations in a buffer. After this has been done, the
Sounds like you mean a "buffer" of 8-bit integers. How are
you representing this "buffer"?

Have a look at the array module. It can construct an array
of signed or unsigned character elements optionally initialized
with values from a list or string. You can operate on elements
of the array using indices, and you can convert the result to
string or list, or you can write it directly to a file. E.g.,
here is an example using unsigned chars:

Get the array module:
 >>> import array

Make an array of unsigned chars, initialized from a list:
 >>> nums = array.array('B',[65,66,67,0,1,2,3])
 >>> nums
 array('B', [65, 66, 67, 0, 1, 2, 3])

Look at it as a string:
 >>> nums.tostring()
 'ABC\x00\x01\x02\x03'

Convert to actual list:
 >>> nums.tolist()
 [65, 66, 67, 0, 1, 2, 3]

Now we'll mess with the [2] element (67) in the array:
 >>> nums[2]+=1
 >>> nums
 array('B', [65, 66, 68, 0, 1, 2, 3])

Result as string (note C->D):
 >>> nums.tostring()
 'ABD\x00\x01\x02\x03'

>buffer has to ba written to a binary file (and file.write 
>takes strings instead of lists).
>
Check doc string for .tofile() method:
 >>> print nums.tofile.__doc__
 tofile(f)

So:
 >>> f=file('abdetc.txt','wb') # write binary
 >>> nums.tofile(f)
 >>> f.close()

Now read it back into a string
 >>> f=file('abdetc.txt','rb') # read binary
 >>> numstr = f.read()
 >>> numstr
 'ABD\x00\x01\x02\x03'

This gets you the whole string without an exception,
whereas you can read an exact number of characters
using the .fromfile() method, if you know how many you want.

Use as string, and/or convert to another array:
 >>> nums2=array.array('B',numstr)
 >>> nums2
 array('B', [65, 66, 68, 0, 1, 2, 3])

We've gone full circle:
 >>> nums2.tostring()
 'ABD\x00\x01\x02\x03'

Or, you could do something else with the file, e.g.,
seek past two bytes in the file and get three bytes into an array
of unsigned chars:
 >>> f=file('abdetc.txt','rb') # read binary
 >>> f.seek(2)

Make empty array:
 >>> nums3=array.array('B')
 >>> nums3
 array('B')

Append elements from file:
 >>> nums3.fromfile(f,3)
 >>> nums3
 array('B', [68, 0, 1])

See as string again:
 >>> nums3.tostring()
 'D\x00\x01'

You can also do all this without the array module, with
lists of numbers, converting to chars and strings:

 >>> numlist = map(ord,'ABC\x00\x01\x02')
 >>> numlist
 [65, 66, 67, 0, 1, 2]
 >>> map(chr,numlist)
 ['A', 'B', 'C', '\x00', '\x01', '\x02']
 >>> ''.join(map(chr,numlist))
 'ABC\x00\x01\x02'

Regards,
Bengt Richter



More information about the Python-list mailing list