Split Pairs

问题描述:

Split the string into pairs of two characters. If the string contains an odd number of characters, then the missing second character of the final pair should be replaced with an underscore ('_').

(将一个字符串两两分开,最后如果剩一个就加上“_”重新组成一对)

Input: A string.

Output: An iterable of strings.

def split_pairs(a):
    # your code here
    return None


if __name__ == '__main__':
    print("Example:")
    print(list(split_pairs('abcd')))

    # These "asserts" are used for self-checking and not for an auto-testing
    assert list(split_pairs('abcd')) == ['ab', 'cd']
    assert list(split_pairs('abc')) == ['ab', 'c_']
    assert list(split_pairs('abcdf')) == ['ab', 'cd', 'f_']
    assert list(split_pairs('a')) == ['a_']
    assert list(split_pairs('')) == []
    print("Coding complete? Click 'Check' to earn cool rewards!")

对我来说这有点难,split不能用,那就只能用索引,最终有了以下比较繁琐的方法: 

def split_pairs(a):
    # your code here
    lst=[]
    lst_index=0
    if len(a)%2==0:
        for i in range(len(a)//2):
            lst.append(a[lst_index:lst_index+2])
            lst_index+=2
    elif len(a)%2==1:
        for i in range(len(a)//2):
            lst.append(a[lst_index:lst_index+2])
            lst_index+=2
        lst.append(a[-1]+'_')
    return lst

其他解决方案:

一:对我上面想法的一个更优版。

def split_pairs(a):
    # your code here
    if a == '':
        return []
    if len(a) % 2 == 1:
        a = a + "_"

    b = [a[i:i+2] for i in range(0, len(a), 2)]
    return b

 

二:很简单的一行,但是用了zip,一个对我来说新的知识点。

def split_pairs(a):
    return [ch1+ch2 for ch1,ch2 in zip(a[::2],a[1::2]+'_')]

官方文档解释:

zip(*iterables)

创建一个聚合了来自每个可迭代对象中的元素的迭代器。

返回一个元组的迭代器,其中的第 i 个元组包含来自每个参数序列或可迭代对象的第 i 个元素。 当所输入可迭代对象中最短的一个被耗尽时,迭代器将停止迭代。 当只有一个可迭代对象参数时,它将返回一个单元组的迭代器。 不带参数时,它将返回一个空迭代器。

也就是说两个列表中的相同索引会在一起。而当上面输入的一个偶数长度的字符串时,多余的'_'并不会被组合到一起,这个真的是很厉害。

三:还有一个新的库,textwrap文本自动换行与填充

from textwrap import wrap

def split_pairs(a):
    a = a + '_' if len(a) % 2 else a
    return wrap(a, 2)

 textwrap 模块提供了一些快捷函数,以及可以完成所有工作的类 TextWrapper。 如果你只是要对一两个文本字符串进行自动换行或填充,快捷函数应该就够用了;否则的话,你应该使用 TextWrapper 的实例来提高效率。

textwrap.wrap(textwidth=70*initial_indent=""subsequent_indent=""expand_tabs=Truereplace_whitespace=Truefix_sentence_endings=Falsebreak_long_words=Truedrop_whitespace=Truebreak_on_hyphens=Truetabsize=8max_lines=None)

对 text (字符串) 中的单独段落自动换行以使每行长度最多为 width 个字符。 返回由输出行组成的列表,行尾不带换行符。

这个也是处理这个问题很好的方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值