0

For example I have a string:

word = '__________'

And I wanted to change the character e to I using replace but not by the letter but using index position of e which is 5

new = word.replace(n[5], 'i')
print(new)

Which won't work and give me an output like this

>>>iiiiiiiiii

Is there any way to replace a string using the index position?

4 Answers4

0

Just replace n with word:

word = 'coordenate'
new = word.replace(word[5], 'i')
print(new)

Output:

>>>coordinati

or you want to change the value by index:

word = '__________'
tmp = list(word)
tmp[5] = 'i'
new = ''.join(tmp)
print(new)

Out put:

_____i____
0

Try this:

def replace_by_index(string, idx, character):
    return string[:idx] + character + string[idx+1:]

be careful to use only valid indexes, otherwise the character will be appended to the end of the word (or to the beginning if large negative values are used).

azelcer
  • 1,383
  • 1
  • 3
  • 7
0

A string is an immutable object, which means that you cannot directly change a letter into a string through its index.

In your example, you have ask to replace all occurences of the 6th letter, hence the result.

To change a specific letter I can imagine 2 ways:

  1. use slices to separate before, the letter itself and after:

     new = word[:5] + 'i' + word[6:]
    
  2. convert the string to a mutable sequence type like list

     data = list(word)
     data[5] = 'i'
     new = ''.join(data)
    
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
0

Try this,

word = "coordenate"
new = word.replace(word[5],'i',1)
print(new)

Output is :

coordinate
Yash verma
  • 56
  • 5