Python Forum
the quest for a mutable string (buffer) - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: General (https://python-forum.io/forum-1.html)
+--- Forum: News and Discussions (https://python-forum.io/forum-31.html)
+--- Thread: the quest for a mutable string (buffer) (/thread-41896.html)



the quest for a mutable string (buffer) - Skaperen - Apr-04-2024

so often i am taking some logic from some program not in Python and need to implement it in Python. so many of these programs are constructing strings by putting string parts in over other string parts to end up with the desired result as a mutated string. this is simple to do in C. in Python, i can do this wit type bytearray. but, to do that i have to burden my code with all this string to bytes and bytes to string conversion. another way i have used was a list where i should have just on character in each spot of the list, but could end up with more by unintentionally inserting strings long than 1 into the list spot.

bytearray seems safer. list makes more sense unless the program otherwise needs to work with byte. i am trying to decide which method i should use, to commit to a full set of tools. one tool would be a string and bytes combiner which would concatenate all it arguments and return a bytearray. strings would by converted to bytes as needed. another tool would be like that except prints the result.

which way do you think this should be done and why?


RE: the quest for a mutable string (buffer) - Gribouillis - Apr-04-2024

You could perhaps use numpy arrays as mutable strings
>>> import numpy as np
>>> s = np.fromiter('hello world', dtype='U1')
>>> t = np.fromiter('spam', dtype='U1')
>>> s
array(['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'], dtype='<U1')
>>> t
array(['s', 'p', 'a', 'm'], dtype='<U1')
>>> s[1:5] = t
>>> s
array(['h', 's', 'p', 'a', 'm', ' ', 'w', 'o', 'r', 'l', 'd'], dtype='<U1')
>>> ''.join(s)
'hspam world'



RE: the quest for a mutable string (buffer) - Skaperen - Apr-04-2024

that looks like a possibility. but it also looks like using a list. i think i need to try it and see how well it works. i do want to avoid having to code 'foobar' as 'f','o','o','b','a','r'. things that get 'foobar' in some form need to be able to accept it as if it got 'f','o','o','b','a','r'.