0

I am having troubles getting my function to return a specified length containing repetitions of a specific value.

Example.

def myString(v, 5)
>>> v v v v v 
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
AEL
  • 45
  • 2
  • 5

2 Answers2

2

Use multiplication:

>>> v = 'v'
>>> v * 5
'vvvvv'

If you need spaces in between, use a list and join the output with a space:

>>> ' '.join([v] * 5)
'v v v v v'
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

The syntax for your definition is wrong, which may be causing some of your trouble. Here is a complete function that will run with the join() command:

def makestring(mychar, num):
   return " ".join([mychar] * num)

makestring('v', 5)

If you are trying to learn the language, here is another example that may help. The version below is much less efficient, but builds the string in a manner that may be easier to follow. You should be able to see how the string is built one character at a time:

def makestring(mychar, num):
    mystr = ""
    for i in range(num-1):
        mystr = mystr + mychar + " "
    mystr = mystr + mychar
    return mystr

makestring('v', 5)
Kevin
  • 2,112
  • 14
  • 15