简体   繁体   中英

Replacing a character in a string using index - Python

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?

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____

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

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)

Try this,

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

Output is:

coordinate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM