如何按位置将变量插入字符串

how to insert variable into string by position

如何按位置将变量插入字符串, 例如在string

中插入a

string = "Hello World"

a = '@'

position = 3

输出>>> Hel@lo World

您可以使用切片:

a = '@'
position = 3
string = "Hello World"
new = string[:position] + a + string[position:]

你可以使用这个:

str_1 = "Hello World"

def insert_str(org_str, insert_str, pos):
    str_2 = list(org_str)
    str_2.insert(pos, insert_str)
    new_string = "".join(str_2)
    return new_string

a = '@'
position = 3

new_string = insert_str(org_str=str_1, insert_str=a, pos=position)
print(new_string)
str_1="Hello World"
st=list(str_1)
st.insert(pos,a)
str_1="".join(st)

您可以先将列表转换为字符,这些字符将存储在列表中,您可以在列表中添加任意数量的元素,然后最后使用 .join()

获取修改后的字符串