7

I want to do something like this.

example_string = "test"
print(example_string.replace(example_string[0], "b"))

expecting the output

best

however because the letter "t" is being passed into the method the t at the end also gets replaced with a "b". Resulting in the output

besb

How do I do it in a way that would result in the output "best" instead of "besb"?

4
  • 1
    You may want to try something like new_str = "b" + example_string[1:] . replace(a,b) is used for swapping all occurrences of string a with b. Commented Aug 9, 2016 at 21:15
  • I don't understand, you want to substitute the first 't' character of a string with 'b' ? Or is the index the key to decide what to replace (instead of the t) Commented Aug 9, 2016 at 21:15
  • @Lynch: That's for replacing the first occurrence of a substring, not a specific occurrence of a substring. Commented Aug 9, 2016 at 21:19
  • I cant answer because its closed, but now I understand. This should works: word = "test"; i = word.index('t', 2); word[0:i] + "b" + word[i+1:]. Of course if you know the id of the char you want to replace instead of a letter you can directly set the variable i. If you need to substitue strings you could adapt it using the i+len(substring)+1 to determine where the string ends. Commented Aug 9, 2016 at 21:34

3 Answers 3

11

The problem is that .replace(old, new) returns a copy of the string in which the occurrences of old have been replaced with new.

Instead, you can swap the character at index i using:

new_str = old_str[:i] + "b" + old_str[i+1:]
Sign up to request clarification or add additional context in comments.

Comments

5

Check the documentation.

You can use

example_string.replace(example_string[0], "b", 1)

though it would be much more natural to use a slice to replace just the first character, as @nbryans indicated in a comment.

2 Comments

That works for this case, but then what if you want to replace example_string[3]?
Note that your question was specifically how to replace the first occurrence of a character. (see XY Problem) This is a different question. Don't use replace() where it is not appropriate, then. As noted, use slices when you want to act upon a particular location of a string (or other sequence such as a list or tuple). So for your new question: s = example_string[:3] + "b" + example_string[4:]
1
example_string.replace("t", "b", 1)

1 Comment

That works for this case, but then what if you want to replace example_string[3]?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.