Repeating Characters in the Middle of a String

旧巷老猫 提交于 2019-12-13 09:45:57

问题


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), and it should return a new string which will have the middle character/s in the string repeated as many times as the length of the input (original) string. Notice that if the original string has an odd number of characters there is only one middle character. If, on the other hand, if the original string has an even number of characters then there will be two middle characters, and both have to be repeated (see the example).

Additionally, if there is only one middle character, then the string should be surrounded by 1 exclamation sign in each extreme . If, on the other hand, the original string has two middle characters then the output (or returned) string should have two exclamation signs at each extreme.

As an example, the following code fragment:

print repeat_middle("abMNcd")`

should produce the output:

!!MNMNMNMNMNMN!!

回答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!


来源:https://stackoverflow.com/questions/28736790/repeating-characters-in-the-middle-of-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!