i want to create a string S , which can be used as an array , as in each element can be used separately by accesing them as an array.
-
1You should add more details. Python strings are already working like lists. What exactly do you want? Provide an example, a context, a problem, so that one understands what you're after.Olivier Verdier– Olivier Verdier2010-04-10 07:32:47 +00:00Commented Apr 10, 2010 at 7:32
3 Answers
You can convert a string to a list of characters by using list, and to go the other way use join:
>>> s = 'Hello, world!'
>>> l = list(s)
>>> l[7] = 'f'
>>> ''.join(l)
'Hello, forld!'
5 Comments
I am a bit surprised that no one seems to have written a popular "MutableString" wrapper class for Python. I would think that you'd want to have it store the string as a list, returning it via ''.join() and implement a suite of methods including those for strings (startswith, endswith, isalpha and all its ilk and so one) and those for lists.
For simple operations just operating on the list and using ''.join() as necessary is fine. However, for something something like: 'foobar'.replace('oba', 'amca') when you're working with a list representation gets to be ugly. (that=list(''.join(that).replace(something, it)) ... or something like that). The constant marshaling between list and string representations is visually distracting.