温馨提示×

python中怎么用replace替换指定位置的字符

小亿
100
2024-04-01 21:15:06
栏目: 编程语言

要替换指定位置的字符,可以先将字符串转换为列表,然后使用索引来替换指定位置的字符,最后再将列表转换回字符串。

以下是一个示例代码:

def replace_char_at_index(input_string, index, replacement):
    if index < 0 or index >= len(input_string):
        return "Index out of range"
    
    string_list = list(input_string)
    string_list[index] = replacement
    return ''.join(string_list)

input_string = "hello world"
index = 6
replacement = 'X'
result = replace_char_at_index(input_string, index, replacement)
print(result)  # 输出: hello Xorld

在上面的示例中,replace_char_at_index函数接受一个字符串、一个索引和一个替换字符作为参数,然后将字符串转换为列表并替换指定位置的字符,最后将列表转换回字符串并返回替换后的结果。

0