-1

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
martineau
  • 119,623
  • 25
  • 170
  • 301
  • "but this code doesn't:" The trick is that each `'cat'` has to be a **separate argument** to `print`. That's what the unpacking `*` operator is useful for. – Karl Knechtel Oct 06 '22 at 06:39

5 Answers5

5

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)))
user2390182
  • 72,016
  • 6
  • 67
  • 89
5

You are looking for print('petting'.join(["cat"]*3))

$ python3
Python 3.6.9 (default, Jan 26 2021, 15:33:00) 
[GCC 8.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> print('petting'.join(["cat"]*3))
catpettingcatpettingcat
>>> 
rok
  • 9,403
  • 17
  • 70
  • 126
0

Function returning a string object

def repeat(word, n, sep='&'):
    return sep.join(word for _ in range(n))

print(repeat('Hallo', 3))

Output

hallo&hallo&hallo
cards
  • 3,936
  • 1
  • 7
  • 25
0

To repeat the word you can use a loop and a variable to store the output of your repeat method. Here is an example of how you could implement it.

def repeat(word, n, delim):
    str = ''
    for i in range(n): # this will repeat the next line n times.
        str += word + delim 
    return str[0:len(str) - len(delim)] # len(delim) will remove the last 'delim' from 'str'. 

In your main method, you will need to print what is returned from the repeat method. For example:

print(repeat(string, n, delim))
David
  • 33
  • 1
  • 7
0

You can try this out

def myprint(word, n, delim):
    ans = [word] * n 
    return delim.join(ans)
    
print(myprint('cat',3,'petting'))
catpettingcatpettingcat
Ram
  • 4,724
  • 2
  • 14
  • 22