0
def main() :
    n = 5
    def repeat(string, n, delim) :

        name = "string" + "delim"
    nametwo = name * n
    print(nametwo)

I need to write a function def repeat(string, n, delim) which returns the string "string"repeated n times, separated by the string deli. exampleL repeat("ho", 3, ", ") "ho, ho, ho"Could someone give me tips how i should go along of writing this?

2
  • what's your current attempt? Commented Oct 9, 2013 at 0:29
  • 4
    Presuming that the line nametwo = name * n is intended to be part of the function repeat(), this almost does what you want - the only thing left to do is to remove the last delim from the string before returning it - look up "string slicing" to do that. Commented Oct 9, 2013 at 0:33

6 Answers 6

3

Look at this:

>>> ", ".join("ho" for _ in range(3))
'ho, ho, ho'
>>> def repeat(string, n, delim):
...     return delim.join(string for _ in range(n))
...
>>> repeat("ho", 3, ", ")
'ho, ho, ho'
>>>

Mainly, this takes advantage of the join method of a string and the range built-in.

Sign up to request clarification or add additional context in comments.

13 Comments

also ("ho,"*5)[:-1]
@FooBarUser: [:-1] isn't very useful if the delimiter is more than one character, as it is in every example on this page…
I haven't quite learned the join term yet, along with xrange. if i used it without the terms would it look something like this? def main() : n = input("enter amount of repeats: ") ba = "ho" ca = ", " def repeat(ba, n, ca) : return (sorry for the layout, i haven't quite learned how to set it as a code in a comment)
@iCodez: How many times have you written dir + '/' + file just this once because it's not worth importing os for something this simple, and then it grows into a real program and suddenly you have Windows users with all kinds of bugs that make no sense and the next thing you know Posh Spice has been elected President of the US? OK, probably not too many, in fact, probably 0, but still, use the batteries when they help.
@iCodez, that's really not a good reason to not use itertools. Have you measured how long it takes to import? Or do you mean it's extra typing?
|
3

What you're asking for already exists: str.join. join is only doing the hard part; we still need something for the easy part… but that's the easy part.

Also, as others have pointed out, you can use the * operator on strings to get you most of the way there. But, despite having nearly written that yourself, I get the feeling you don't understand why that's most of the way there.

You can even combine the two: delim.join([string] * n). (Here, I'm repeating a list rather than the string itself, because otherwise I'd just get one big string "spamspamspamspamspam" instead of five separate "spam"s to join up.)


But, I'm going to assume this is a homework assignment or a self-teaching attempt, and you want to know how to write it yourself from scratch.

Normally, when you want to repeat something, you want a loop.

If you want to repeat something for each element in the list spam, you write the loop for element in spam:.

But what if you want to repeat it 5 times? There's no "each element in the number 5". You need for find something that has 5 elements. And range(5) is perfect for that. So:

def repeat(string, n, delim):
    for i in range(n):
        # something

Next, you already know how to concatenate strings, with the + operator. So, let's start with an empty string, and concatenate onto the end of it:

def repeat(string, n, delim):
    result = ""
    for i in range(n):
        result = result + string + delim
    return result

But this has a problem:

>>> repeat("spam", 5, ", ")
'spam, spam, spam, spam, spam, '

There's just the right amount of spam, but too many commas.

If you go back to the * solution, you'll see that this is the same thing as (string + delim) * n, we just got there the long way. Either way, you get the same problem.


How do you avoid that?

Here you have to get a bit tricky. You can treat the last value special, or the first one. Or you can look at result so far to see if you're at the start. Or you can just let it add the extra delimiter and then lop it off at the end. I'll show you one of those options, but you should try to write another one yourself. (Looking at result is probably the easiest, and the cleanest, once you figure out how to adjust the algorithm to make it possible.)

def repeat(string, n, delim):
    result = ""
    for i in range(n):
        result = result + string + delim
    return result[:-len(delim)]

The way I lopped off the extra delimiter at the end was by using slicing, with a negative index. You probably haven't learned that yet, which is why you should write a solution for yourself. (Plus, this is probably the hackiest of the solutions.)

Going all the way back to the top, if you play around with join, you'll see that it solves this problem for you. It's obviously not using magic, so you might think about looking at how it's implemented. Unfortunately, it's probably a big mess of C code somewhere in this file, not nice clear Python, so you probably wouldn't learn much.

2 Comments

i really appreciate you taking the time to help me, i have one thing though that I'm a little confused on, i understand the steps of your code, but how do i go along of testing it like you did with your spam example? when i switch the value of n, and run it in my terminal i get no results.
@Brandon: I started an interactive Python session, then typed the lines of the repeat definition, then typed repeat("spam", 5, ", "), and it gave me the output. The interactive session always shows you the value of each thing you type, unless the value is None (or you type a statement, which has no value). If you're putting this in a script and running it, you'll need to add a print statement to get the output printed out. For example: you could write spam5 = repeat("spam", 5, ", "), then print(spam5).
1

You're so close..

def repeat(string, n, delim):
      name = string + delim
      nametwo = name*n
      print(nametwo)

You don't need the quotes there. With the quotes, the value of name will be "stringdelim", instead of the values of "string" and "delim".

1 Comment

This will add the delimiter onto the end of the string - I'm not sure if that's desired
0
>>> def repeat(s, n, d):
...     return d.join([s]*n)
... 
>>> repeat("ho", 3, ", ")
'ho, ho, ho'

You can avoid the temporary list (n might be very large) by using itertools.repeat

>>> import itertools as it
>>> def repeat(s, n, d):
...     return d.join(it.repeat(s, n))
... 
>>> repeat("ho", 3, ", ")
'ho, ho, ho'

Comments

0

Here is a recursive version

def repeat(s, n, d):
    if n == 0:
        return ""
    if n == 1:
        return s
    return repeat(s, n/2, d) + d + repeat(s, n - n/2, d)

Comments

0
def repeat(string, n, delim):
    print((string + delim)*(n-1) + string*(n>0))

>>> repeat('ho', 5, ", ")
ho, ho, ho, ho, ho

1 Comment

Does this give the correct result for n=0?