python在字符串中指定位置插入字符
在Python中,可以使用切片操作和字符串拼接来在字符串中指定位置插入字符。
以下是一个示例代码:
def insert_char(string, char, index):
return string[:index] + char + string[index:]
string = "Hello World"
char = ","
index = 5
new_string = insert_char(string, char, index)
print(new_string)
输出结果为:
Hello, World
在上面的代码中,insert_char函数接受三个参数:原始字符串、要插入的字符和要插入的位置索引。
函数中使用切片操作将原始字符串分成两部分:从开头到指定位置索引之前的部分和从指定位置索引到末尾的部分。然后,使用字符串拼接将这两部分和要插入的字符拼接在一起,得到插入字符后的新字符串。最后,返回新字符串。
在示例中,我们将字符“,”插入到字符串“Hello World”的索引位置5处,得到新字符串“Hello, World”
原文地址: https://www.cveoy.top/t/topic/hytl 著作权归作者所有。请勿转载和采集!