Python replace function
Solution 1
There's no built-in solution. But here's a simple function that does it:
>>> def replace_one_char(s, i, c):
... return s[:i] + c + s[i + 1:]
...
>>> replace_one_char('foo', 1, 'a')
'fao'
Also consider Ignacio's bytearray solution.
Solution 2
No. str.replace()
replaces all instances of that character. Use a bytearray
instead.
>>> test = bytearray('10010')
>>> test[2] = '1'
>>> str(test)
'10110'
Solution 3
Strings are not mutable, thus you'll never find a way to replace just one character of the string. You should use arrays to be able to replace only the nth element.
Replace on strings works in this way:
mystr = "mystr"
mystr.replace('t','i',1)
'mysir'
print mystr
mystr
could be what you need, could be not.
Solution 4
Strings in python are unfortunately immutable, so you have to work with one of a few workarounds to do so.
The byte array method which has been mentioned will work.
You can also work with the string as a list:
s = list("10010")
s[2] = '1'
test = "".join(s)
Splitting is another option:
s = '10010'
s = s[:2] + '1' + s[3:]
Finally, there is string.replace, which several people have mentioned. While you can specify the number of instances of the substring to replace, you can't replace an arbitrary substring with it, so it will not work for your purposes.
user1120190
Updated on April 25, 2020Comments
-
user1120190 about 4 years
I want to use the replace function however I only want to replace one character, not all instances of that character.
For example :-
>>> test = "10010" >>> test = test.replace(test[2],"1") >>> print test >>> '11111' #The desired output is '10110'
Is there a way that I can do this?