-2

So I am trying to learn Python and was wondering how to repeat the char at an index given as an argument in a string. An example would be below

def repeatchar(origString, repeatCount, lettersToRepeat)

>>> repeatChar('cat', 3, 'cr')

'cccat'

I have the comparison of origString and lettersToRepeat. I am trying to figure out how to get the char that is in lettersToRepeat to actually repeat repeatCount times.

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
  • Also, your question says you want to repeat the character at the given index but your code seems to take letters and repeat _those letters_. Which is it? Hint: You need to _find_ any occurrences of _each letter_ in `lettersToRepeat` and _replace_ with that letter repeated `repeatCount` times – Pranav Hosangadi Sep 16 '21 at 16:09
  • I answered as there is a nice 1 liner, but probably worth doing a bit of learning elsewhere. There's plenty of tutorials online to get you going. – s_pike Sep 16 '21 at 16:16

2 Answers2

1

Here's a succinct way to do it:

def repeatChar(origString, repeatCount, lettersToRepeat):
    return "".join([l * repeatCount if l in lettersToRepeat else l for l in origString])

In python strings can be iterated over. This also uses list comprehension, which you might want to look up if you haven't seen before. Here the code between then square brackets produces a list. The "".join() will concatenate the characters in the list together (see: How to concatenate items in a list to a single string?).

s_pike
  • 1,710
  • 1
  • 10
  • 22
0

You could use a recursive approach that performs the repetition for the first character (using replace()) and recurses for the rest of the letters:

def repeatChar(origString, repeatCount, lettersToRepeat):
    if not lettersToRepeat: return origString
    repeated = origString.replace(lettersToRepeat[0],lettersToRepeat[0]*repeatCount)
    return repeatChar(repeated,repeatCount,lettersToRepeat[1:])


repeatChar('cat', 3, 'cr') # 'cccat'
Alain T.
  • 40,517
  • 4
  • 31
  • 51