How can one copy python string characters to array.array
?
from array import array
b = array('b', [0]*30)
s = 'abc'
# What should one do here to copy integer representation of 's' characters to 'b' ?
The integer representation of s
characters should make sense to C : i.e. if I convert the integers in b
to C char
string, I should get back "abc".
The best idea I have is below (but it would be good avoid explicit python loops):
for n,c in enumerate(s): b[n] = ord(c)
Thank you very much for your help!
CodePudding user response:
try clearing it and filling it again:
for i in range(29,-1,-1):
b.pop(i)
len0s = 29 - len(s)
s_lst = [*s] ['\0'] [0]*len0s
b.fromlist(s_lst)
should work if s is under 30 characters
array methods from https://pythongeeks.org/python-array-module/
CodePudding user response:
You can do this if you have the 30-byte array populated ahead of time:
b = array('b', bytes(s, 'utf-8') b[len(s):])
Or if you want to make it from scratch:
b = array('b', bytes(s, 'utf-8') b'\0' * (30 - len(s)))
Or using the struct
module:
struct.pack_into('30s', b, 0, bytes(s, 'utf-8'))