Home > OS >  Replacing a character in a string using index - Python
Replacing a character in a string using index - Python

Time:12-09

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?

CodePudding user response:

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).

CodePudding user response:

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)
    

CodePudding user response:

Try this,

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

Output is :

coordinate

CodePudding user response:

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____
  • Related