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?
Use the translate() method to replace multiple different characters. You can create the translation table specified in translate() by the str. maketrans() .
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
TypeError: 'str' object does not support item assignment
This is to be expected - python strings are immutable.
One way is to do some slicing and dicing. Like this:
>>> aa = 'abcdefghijkl'
>>> changed = aa[0:-2] + 'A' + aa[-1]
>>> print changed
abcdefghijAl
The result of the concatenation, changed
will be another immutable string. Mind you, this is not a generic solution that fits all substitution scenarios.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With