Home > database >  Python function that prints n times string s1 separated by string s2
Python function that prints n times string s1 separated by string s2

Time:11-12

I'm stuck with this problem for a few days. I wanna create a function that does this with only one line of code:

>>> func1(1, '*', '-')
'*'
>>> func1(2, '*', '-')
'**-**'
>>> func1(3, '*', '-')
'***-***-***'
>>> func1(4, 'z', 'Z')
'zzzzZzzzzZzzzzZzzzz'

So I thought of something like this:

def func(n, s1, s2):
    print(n * (n * s1   s2)

Which would print this:

>>>func(2, '*', '-')
**-**-

Is there any way to get rid of the last "-"?

CodePudding user response:

you could simply not print the last element

def func(n, s1, s2):
    print((n * (n * s1   s2))[:-len(s2)])

CodePudding user response:

You can use join.

>>> def func(n, s1, s2):
...     return s2.join([s1 * n] * n)

Usage:

>>> func(1, '*', '-')
'*'
>>> func(2, '*', '-')
'**-**'
>>> func(3, '*', '-')
'***-***-***'
>>> func(4, 'z', 'Z')
'zzzzZzzzzZzzzzZzzzz'
  • Related