0

Ive tried using .replace() but when I use an index to define the character being replaced, it replaces all of the characters that are the same as the one being indexed as shown here:

string = "cool"
print(string.replace(string[1], "u"))

if returns:

"cuul"

But I just want the specific character which the index of string[1] to be replaced, for example, I want it to work as such:

string = "cool"
print(substitute(string[1],"u")

such that it prints:

"cuol"
Marcus Dev
  • 26
  • 2
  • I would turn the string into a list, replace the character, and turn it back into a string again, but I don't know whether that is what you are looking for. ```string = list(string); string[1] = "u"; string = "".join(string)``` – Armadillan Jan 15 '21 at 04:24

3 Answers3

0

This should work :

stirng1 = "cool"
list1 = list(string1)
list1[1] = "u"
print("".join(list1))

When executed :

>>>cuol
CopyrightC
  • 857
  • 2
  • 7
  • 15
0

What you are trying to do is search for string[1] which is o and replace all instances of o with u.

string = "cool"
print(string.replace(string[1], "u"))
# cuul

The issue is that string objects are immutable, so you will just have to create a new string that includes the value at the desired index.

index = 1
char = 'u'

print(string[:index] + char + string[index+1:])
#cuol
Akshay Sehgal
  • 18,741
  • 3
  • 21
  • 51
0
def substitute(string,index,char):
    strlist = list(string)
    strlist[index] = char
    return ''.join(strlist)
Matt Miguel
  • 1,325
  • 3
  • 6