> 文章列表 > python代码,在字符串的多个指定位置插入符号

python代码,在字符串的多个指定位置插入符号

python代码,在字符串的多个指定位置插入符号

可以使用循环和字符串的切片操作以及字符串的拼接操作来在字符串的多个指定位置插入符号-

以下是一个在字符串多个指定位置插入符号-的示例代码:

def insert_dash(s, indices):sorted_indices = sorted(indices)new_s = sfor i in range(len(sorted_indices)):new_s = new_s[:sorted_indices[i]+i] + '-' + new_s[sorted_indices[i]+i:]return new_s

在这个函数中,输入参数s是一个字符串,indices是需要在字符串中插入符号-的位置的列表。函数返回在多个指定位置插入符号-后的新字符串。

该函数首先将需要插入符号-的位置进行排序,然后使用循环和字符串的切片操作以及字符串的拼接操作,在每个指定位置插入符号-。由于插入符号-后,后面的位置会发生变化,因此在循环中需要调整插入符号-的位置。最后返回插入后的新字符串。

以下是一个使用示例:

s = 'hello world'
indices = [1, 4, 7]
new_s = insert_dash(s, indices)
print(new_s)  # 输出 'h-e-llo-w-orld'

在这个示例中,输入字符串为'hello world',需要在第2、5、8个位置插入符号-。函数返回结果为'h-e-llo-w-orld',表示在多个指定位置插入符号-后的新字符串为'h-e-llo-w-orld'