Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to substitute part of a string in python?

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?

like image 517
user63503 Avatar asked Aug 23 '10 18:08

user63503


People also ask

How do you replace multiple parts of a string in Python?

Use the translate() method to replace multiple different characters. You can create the translation table specified in translate() by the str. maketrans() .


2 Answers

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
like image 91
eldarerathis Avatar answered Sep 16 '22 18:09

eldarerathis


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.

like image 40
Manoj Govindan Avatar answered Sep 18 '22 18:09

Manoj Govindan