Skip to content Skip to sidebar Skip to footer

Repeating Characters In The Middle Of A String

Here is the problem I am trying to solve but having trouble solving: Define a function called repeat_middle which receives as parameter one string (with at least one character), an

Solution 1:

def repeat_middle(text):
    a, b = divmod(len(text) - 1, 2)
    middle = text[a:a + b + 1]
    exclamations = '!' * len(middle)
    return '{}{}{}'.format(exclamations, middle * len(text), exclamations)

>>> print repeat_middle("abMNcd")
!!MNMNMNMNMNMN!!

>>> print repeat_middle("abMcd")
!MMMMM!

Post a Comment for "Repeating Characters In The Middle Of A String"