python通过下标替换字符串,指定位置添加字符串

指定下标替换字符串

def replace_char(old_string, char, index):
    '''
    字符串按索引位置替换字符
    '''
    old_string = str(old_string)
    # 新的字符串 = 老字符串[:要替换的索引位置] + 替换成的目标字符 + 老字符串[要替换的索引位置+1:]
    new_string = old_string[:index] + char + old_string[index+1:]
    return new_string

 

指定位置添加字符串

def add_char(old_string, char, index):
    '''
    将字符串按索引位置添加字符
    '''
    old_string = str(old_string)
    # 新的字符串 = 老字符串[:要替换的索引位置] + 替换成的目标字符 + 老字符串[要替换的索引位置+1:]
    new_string = old_string[:index] + char + old_string[index:]
    return new_string

 

文章来自:https://www.cnblogs.com/dapenson/p/14164461.html

posted @ 2022-08-20 23:32  博无止境  阅读(1095)  评论(0编辑  收藏  举报