insert a string into another string at a specific index in python

You can use string concatenation and slicing to insert a string into another string at a specific index. Here's an example:

main.py
string1 = "Hello, world!"
string2 = "beautiful "

# insert string2 into string1 at index 7
new_string = string1[:7] + string2 + string1[7:]

print(new_string) # output: "Hello, beautiful world!"
195 chars
8 lines

In this example, we slice string1 into two parts: string1[:7] contains the characters before the insertion point, and string1[7:] contains the characters after the insertion point. We then concatenate string2 between these two parts to create the new string new_string.

Note that string slicing and concatenation create new strings, so the original strings string1 and string2 are not modified. If you want to replace the original string with the new string, you can assign new_string to string1:

main.py
string1 = new_string
21 chars
2 lines

gistlibby LogSnag