user1120190
user1120190

Reputation: 691

Python replace function

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?

Upvotes: 2

Views: 20299

Answers (5)

rmihno
rmihno

Reputation: 1

test = "10010"
test = test.replace(test[2],"1")
print test
'11111' #The desired output is '10110'

you could something like this

test2= test[0:1]+"1"+test[3:4]

Upvotes: 0

kevintodisco
kevintodisco

Reputation: 5191

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.

Upvotes: 1

jimifiki
jimifiki

Reputation: 5544

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.

Upvotes: 1

senderle
senderle

Reputation: 151187

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.

Upvotes: 4

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799560

No. str.replace() replaces all instances of that character. Use a bytearray instead.

>>> test = bytearray('10010')
>>> test[2] = '1'
>>> str(test)
'10110'

Upvotes: 4

Related Questions