在字符串中间重复字符 [英] Repeating Characters in the Middle of a String

查看:42
本文介绍了在字符串中间重复字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我正在尝试解决但无法解决的问题:

定义一个名为 repeat_middle 的函数,它接收一个字符串(至少有一个字符)作为参数,它应该返回一个新字符串,该字符串中的中间字符将重复多次倍作为输入(原始)字符串的长度.请注意,如果原始字符串具有奇数个字符,则只有一个中间字符.另一方面,如果原始字符串的字符数为偶数,则中间会有两个字符,并且都必须重复(参见示例).

另外,如果只有一个中间字符,那么字符串应该在每个极端用 1 个感叹号包围.另一方面,如果原始字符串有两个中间字符,那么输出(或返回)字符串应该在每个极端都有两个感叹号.

以下面的代码片段为例:

print repeat_middle("abMNcd")`

应该产生输出:

<代码>!!MNMNMNMNMNMN!!

解决方案

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

<小时><预><代码>>>>打印repeat_middle(abMNcd")!!MNMNMNMNMNMN!!>>>打印repeat_middle(abMcd")!嗯!

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

解决方案

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!

这篇关于在字符串中间重复字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆