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?
Asked
Active
Viewed 106 times
-4

Pavel Zagalsky
- 1,620
- 7
- 22
- 52
-
1Show us what you have tried to solve this problem. Does it work? If not, what does not work? – May 02 '18 at 09:40
-
4You have tried exactly zero things, right? – Tomalak May 02 '18 at 09:40
-
2Your question is unclear: do you want to replace the 'u' because it is a 'u' or because it is in 4th position? – Benjamin Barrois May 02 '18 at 09:40
-
Because of the index – Pavel Zagalsky May 02 '18 at 09:41
2 Answers
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
-
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