I am having trouble trying to get my string to repeat the amount of times I want it to.
Here is my code, but I am not sure where I am going wrong.
def respond_echo(input_string, number_of_echoes, spacer):
echo_output = ''
if len(input_string) > 0:
for i in range(number_of_echoes):
echo_output = (input_string spacer) * number_of_echoes
else:
echo_output = None
return echo_output
respond_echo('meow', 3, '~')
'meow~~~meow~~~meow~~~'
It comes out like this but I want it to look like this
'meow~meow~meow~'
CodePudding user response:
I have corrected it. When I tried the code it output meow~meow~meow~meow~meow~meow~meow~meow~meow~
.
The problem is that every time in the for loop you are multiplying the string, so I removed it. The corrected code is:
def respond_echo(input_string, number_of_echoes, spacer):
echo_output = ""
if len(input_string) > 0:
for i in range(number_of_echoes):
echo_output = input_string spacer
else:
echo_output = None
return echo_output
CodePudding user response:
Your code above produces 'meow~meow~meow~meow~meow~meow~meow~meow~meow~'
because it is redundant to both use a for
loop and multiply the string within each for loop using *
. You could do one or the other, but *
is nice and concise.
You almost had it though. Here is a working runnable example!
#!/usr/bin/env python
def respond_echo(input_string, number_of_echoes, spacer):
if input_string:
echo_output = (input_string spacer) * number_of_echoes
return echo_output
respond_echo('meow', 3, '~')
<script src="https://modularizer.github.io/pyprez/pyprez.min.js" theme="darcula"></script>