The insert() method inserts a string into another string.
The insert() method takes two parameters:
str.insert(index, substr)
str: This is the string where we want to insert a new string.
index: This is the index position to start the new string or sub-string insertion.
substr: This is the sub-string we want to insert to the str string.
The value returned is str but with substr inserted into it.
Note: If the index is negative, we count backward to start insertion.
# create some stringsstr1 = "Edpre"str2 = "s"str3 = "awme"# insert substringsr1 = str1.insert(5, "sso") # 6th positionr2 = str2.insert(0, "i") # 1st positionr3 = str3.insert(2, "eso") # 3rd position# print resultsputs r1puts r2puts r3
Line 2 to 4: String variables str1, str2 and str3 are created and initialized.
Line 7: We insert "sso" to the 6th index position of string str1 and store the result in the variable, r1.
Line 8: "i" is inserted to str2 at the first index position. The result is stored inside the variable, r2.
Line 9: "eso" is inserted to the str3 string at the third index position.