在Python中,由于字符串是不可变的,不能直接在字符串中插入一个字符。但是,可以通过以下几种方法实现字符串中字符的插入:
string = "Hello World"index = 5 要插入字符的位置char = " " 要插入的字符new_string = string[:index] + char + string[index:]print(new_string) 输出:Hello World
2. 使用字符串的`join()`方法:

string = "Hello World"index = 5 要插入字符的位置char = " " 要插入的字符new_string = "".join([string[:index], char, string[index:]])print(new_string) 输出:Hello World
3. 使用列表的`insert()`方法,然后将列表转换回字符串:
string = "Hello World"index = 5 要插入字符的位置char = " " 要插入的字符lst = list(string)lst.insert(index, char)new_string = "".join(lst)print(new_string) 输出:Hello World
以上方法都可以实现在Python中插入字符
