Python Forum
the quest for a mutable string (buffer)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
the quest for a mutable string (buffer)
#1
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?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
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'
« We can solve any problem by introducing an extra level of indirection »
Reply
#3
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'.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  the quest for a mutable string (more) Skaperen 0 163 Apr-04-2024, 04:01 AM
Last Post: Skaperen
  quest for better float formatting Skaperen 0 1,029 Mar-02-2022, 08:34 PM
Last Post: Skaperen
  Runtime error: coercing to Unicode: need string or buffer, NoneType found satheesh_rvs 2 3,054 Dec-10-2018, 12:46 PM
Last Post: satheesh_rvs
  mutable strings Skaperen 3 3,510 Dec-03-2017, 03:05 AM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020