114k views
25 votes
write a function insert_string_multiple_times() that has four arguments: a string, an index into the string, a string to insert, and a count. the function will return a string with count copies of the insert-string inserted starting at the index. note: you should only write the function. do not put any statements outside of the function. examples: insert_string_multiple_times('123456789',3,'xy',3) '123xyxyxy456789' insert_string_multiple_times('helloworld',5,'.',4) 'hello....world' insert_string_multiple_times('abc',0,'a',2) 'aaabc' insert_string_multiple_times('abc',0,'a',0) 'abc'

User Andria
by
4.1k points

1 Answer

10 votes

Answer:

Written in Python:

def insert_string_multiple_times(str1,indto,str2,count):

splitstr = str1[:indto]

for i in range(count):

splitstr+=str2

splitstr +=str1[indto:]

print(splitstr)

Step-by-step explanation:

This line defines the method

def insert_string_multiple_times(str1,indto,str2,count):

In the above definition:

str1 represents the string

indto represents index to insert a new string

str2 represents the new string to insert

count represents the number of times str2 is to be inserted

This gets the substring from the beginning to indto - 1

splitstr = str1[:indto]

This performs an iterative operation

for i in range(count):

This appends str2 to the first part of the separated string

splitstr+=str2

This appends the remaining part of the separated string

splitstr +=str1[indto:]

This prints the new string

print(splitstr)

User Brightball
by
4.7k points