how to substitute part of a string in python?

user63503 picture user63503 · Aug 23, 2010 · Viewed 37.4k times · Source

How to replace a set of characters inside another string in Python?

Here is what I'm trying to do: let's say I have a string 'abcdefghijkl' and want to replace the 2-d from the end symbol (k) with A. I'm getting an error:

>>> aa = 'abcdefghijkl'
>>> print aa[-2]
k
>>> aa[-2]='A'

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    aa[-2]='A'
TypeError: 'str' object does not support item assignment

So, the question: is there an elegant way to replace (substitute) with a string symbols inside another string starting from specified position? Something like:

# subst(whole_string,symbols_to_substiture_with,starting_position)

>>> print aa
abcdefghijkl
>>> aa = subst(aa,'A',-2)
>>> print aa
abcdefghijAl

What would be a not-brute-force code for the subst?

Answer

eldarerathis picture eldarerathis · Aug 23, 2010

If it's always the same position you're replacing, you could do something like:

>>> s = s[0:-2] + "A" + s[-1:]
>>> print s
abcdefghijAl

In the general case, you could do:

>>> rindex = -2 #Second to the last letter
>>> s = s[0:rindex] + "A" + s[rindex+1:]
>>> print s
abcdefghijAl

Edit: The very general case, if you just want to repeat a single letter in the replacement:

>>> s = "abcdefghijkl"
>>> repl_str = "A"
>>> rindex = -4 #Start at 4th character from the end
>>> repl = 3 #Replace 3 characters
>>> s = s[0:rindex] + (repl_str * repl) + s[rindex+repl:]
>>> print s
abcdefghAAAl