2

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?

5 Answers 5

4

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

>>> test = bytearray('10010')
>>> test[2] = '1'
>>> str(test)
'10110'
Sign up to request clarification or add additional context in comments.

3 Comments

str.replace can also replace any arbitrary amount of substrings if the optional argument 'maxreplace' is given.
@ktodisco: Sure, but that won't help here since it always counts from the beginning of the replaced string instances, and the second one must be changed.
@ktodisco, I thought the same thing initially, then I reread the question and deleted my answer :)
4

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.

Comments

1

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.

Comments

1

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.

Comments

0
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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.