Reputation: 36394
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.
Upvotes: 1
Views: 198
Reputation: 17500
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.
Upvotes: 0
Reputation: 36191
That's how Python strings already work:
>>> a = "abcd"
>>> a[0]
'a'
>>> a[2]
'c'
But keep in mind that this is read only access.
Upvotes: 5
Reputation: 838076
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!'
Upvotes: 3