[英]Replacing a character in a string using index - Python
例如我有一個字符串:
word = '__________'
我想將字符 e 更改為 I 使用 replace 但不是按字母而是使用 e 的索引 position 是 5
new = word.replace(n[5], 'i')
print(new)
哪個行不通,給我一個像這樣的 output
>>>iiiiiiiiii
有沒有辦法使用索引 position 替換字符串?
只需將n
替換為word
:
word = 'coordenate'
new = word.replace(word[5], 'i')
print(new)
Output:
>>>coordinati
或者您想按索引更改值:
word = '__________'
tmp = list(word)
tmp[5] = 'i'
new = ''.join(tmp)
print(new)
輸出:
_____i____
嘗試這個:
def replace_by_index(string, idx, character):
return string[:idx] + character + string[idx+1:]
注意只使用有效的索引,否則字符將被附加到單詞的末尾(如果使用大的負值,則添加到開頭)。
字符串是一個不可變的 object,也就是說不能通過它的索引直接把一個字母變成一個字符串。
在您的示例中,您要求替換所有出現的第 6 個字母,因此結果。
要更改特定字母,我可以想象兩種方法:
使用切片來分隔之前、字母本身和之后:
new = word[:5] + 'i' + word[6:]
將字符串轉換為可變序列類型,如list
data = list(word) data[5] = 'i' new = ''.join(data)
嘗試這個,
word = "coordenate"
new = word.replace(word[5],'i',1)
print(new)
Output 是:
coordinate
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.