0

I have been asked the change the "d" into "e" except the first d. Here is the string "ddar astronaut. pldase, stop drasing md!" which method do i have to use?

  • Does this answer your question? [Replacing instances of a character in a string](https://stackoverflow.com/questions/12723751/replacing-instances-of-a-character-in-a-string) – Umair Mubeen Sep 16 '21 at 07:47

1 Answers1

0

Try this -

You can find the first occurrence of d with s.find('d')+1 and use that as an index to split the string into 2 parts. Use str.replace on the second part.

s = "ddar astronaut. pldase, stop drasing md!"

idx = s.find('d')+1
s[:idx]+s[idx:].replace('d','e')
'dear astronaut. please, stop erasing me!'
Akshay Sehgal
  • 18,741
  • 3
  • 21
  • 51
  • thanks! so the replace method is only replacing the d after the idx? – biniamingl Sep 16 '21 at 08:00
  • since you dont want to modify the string until the first occurance of `d`, the replace is only for the latter part. Try changing the sentence and printing `s[:idx]` and `s[idx:].replace('d','e')` separately to see whats happening – Akshay Sehgal Sep 16 '21 at 08:01