-4

So I have this string: "My Wurds" and I'd like to replace the u at index 4 with o. what is the proper Python way to do that?

Pavel Zagalsky
  • 1,620
  • 7
  • 22
  • 52

2 Answers2

1

You could build a new string using slices:

s = "My Wurds"
t = s[:4] + "o" + s[5:]
  • -1. it only works for this particular case when input string is "My Wurds". I don't think it is an intent of any program to hardcode input values – Artemious May 02 '18 at 09:46
  • 3
    @Artemious It really isn't difficult to take his example and encode it into a function, t = s[:index] + value + s[index+1:], really no reason for down-voting. – Rohi May 02 '18 at 09:50
  • @Artemious It is: `Because of the index – Pavel Zagalsky` –  May 02 '18 at 09:57
0

If you know the index of u where you need to replace with o, a pretty straight approach would be:

s[:4] + s[4:].replace('u', 'o', 1)

replace('u', 'o', 1) will ensure replace of only first occurance.

Austin
  • 25,759
  • 4
  • 25
  • 48