Alternative to python string item assignment

Question:

What is the best / correct way to use item assignment for python string ?

i.e s = "ABCDEFGH" s[1] = 'a' s[-1]='b' ?

Normal way will throw : 'str' object does not support item assignment

Asked By: w00d

||

Answers:

Strings are immutable. That means you can’t assign to them at all. You could use formatting:

>>> s = 'abc{0}efg'.format('d')
>>> s
'abcdefg'

Or concatenation:

>>> s = 'abc' + 'd' + 'efg'
>>> s
'abcdefg'

Or replacement (thanks Odomontois for reminding me):

>>> s = 'abc0efg'
>>> s.replace('0', 'd')
'abcdefg'

But keep in mind that all of these methods create copies of the string, rather than modifying it in-place. If you want in-place modification, you could use a bytearray — though that will only work for plain ascii strings, as alexis points out.

>>> b = bytearray('abc0efg')
>>> b[3] = 'd'
>>> b
bytearray(b'abcdefg')

Or you could create a list of characters and manipulate that. This is probably the most efficient and correct way to do frequent, large-scale string manipulation:

>>> l = list('abc0efg')
>>> l[3] = 'd'
>>> l
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> ''.join(l)
'abcdefg'

And consider the re module for more complex operations.

String formatting and list manipulation are the two methods that are most likely to be correct and efficient IMO — string formatting when only a few insertions are required, and list manipulation when you need to frequently update your string.

Answered By: senderle

Since strings are “immutable”, you get the effect of editing by constructing a modified version of the string and assigning it over the old value. If you want to replace or insert to a specific position in the string, the most array-like syntax is to use slices:

s = "ABCDEFGH" 
s = s[:3] + 'd' + s[4:]   # Change D to d at position 3

It’s more likely that you want to replace a particular character or string with another. Do that with re, again collecting the result rather than modifying in place:

import re
s = "ABCDEFGH"
s = re.sub("DE", "--", s)
Answered By: alexis

I guess this Object could help:

class Charray(list):

    def __init__(self, mapping=[]):
        "A character array."
        if type(mapping) in [int, float, long]:
            mapping = str(mapping)
        list.__init__(self, mapping)

    def __getslice__(self,i,j):
        return Charray(list.__getslice__(self,i,j))

    def __setitem__(self,i,x):
        if type(x) <> str or len(x) > 1:
            raise TypeError
        else:
            list.__setitem__(self,i,x)

    def __repr__(self):
        return "charray['%s']" % self

    def __str__(self):
        return "".join(self)

For example:

>>> carray = Charray("Stack Overflow")
>>> carray
charray['Stack Overflow']
>>> carray[:5]
charray['Stack']
>>> carray[-8:]
charray['Overflow']
>>> str(carray)
'Stack Overflow'
>>> carray[6] = 'z'
>>> carray
charray['Stack zverflow']
Answered By: Pedro
s = "ABCDEFGH" s[1] = 'a' s[-1]='b'

you can use like this

s=s[0:1]+'a'+s[2:]

this is very simple than other complex ways

Answered By: RaM PrabU
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.