Search code examples
pythonpython-3.xstringrepeat

Writing a function that repeats a string n times and separates each repetition with another string


I'm trying to write a function that needs 3 inputs: a string (named word), an integer (named n), another string (named delim', then the function must repeats the string named word n times (and that's easy) and between each repetition it has to insert the string named delim.

I know that this code works:

print('me', 'cat', 'table', sep='&')

but this code doesn't:

print(cat*3, sep='&')

The code I wrote is pretty much useless but I'll post it anyway — there could be other errors or inaccuracies that I'm not aware of.

def repeat(word, n, delim):
    print(word*n , sep=delim)

def main():
    string=input('insert a string:  ')
    n=int(input('insert number of repetition:  '))
    delim=input('insert the separator:  ')

    repeat(string, n, delim)

main()

For example, given this input:

word='cat', n=3, delim='petting'

I would like the program to give back:

catpettingcatpettingcat

Solution

  • You can use iterable unpacking and only use the print function:

    def repeat(word, n, delim):
        print(*n*[word], sep=delim)
    

    Or just use str.join:

    def repeat(word, n, delim):
        print(delim.join(word for _ in range(n)))