Is there an object that acts like array.array, yet can handle strings (or character arrays) as its data type?
It should be able to convert the string array to binary and back again, preferably with null terminated strings, however fixed length strings would be acceptable.
>>> my_array = stringarray(['foo', 'bar'])
>>> my_array.tostring()
'foo0円bar0円'
>>> re_read = stringarray('foo0円bar0円')
>>> re_read[:]
['foo', 'bar']
I will be using it with arrays that contain a couple million strings.
asked Mar 31, 2012 at 5:18
Gladius
3691 gold badge3 silver badges14 bronze badges
1 Answer 1
Simply use a standard Python list:
def list_to_string(lst):
return "0円".join(l) + "0円"
def string_to_list(s):
return s.split("0円")[:-1]
answered Mar 31, 2012 at 5:22
Sven Marnach
608k123 gold badges969 silver badges866 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
Gladius
I will need to keep 0円 to specify empty strings. s.split('0円')[:-1] ?
Sven Marnach
@Gladius: I edited the answer to use what you suggested. I didn't use this right away because it will drop the last element even if
s does not end with a 0円.Gladius
Since I will be creating the serialised string, I can be sure that it will always end in 0,円 though extra caution could be used with something like "if s[-1] == '0円' return s[:-1] else return s"
Gladius
This ended up working for my use case. Serialising 10M strings takes ~.30 seconds, de-serialising takes longer at ~.60 seconds. Thanks!
lang-py
'0円'? What are you planning to do with the joined-up string-chunks?