在python中重塑字符串

时间:2019-01-10 07:53:47

标签: python python-3.x

我有一个编码问题,我需要在其中创建函数以对字符串进行整形/重组,并用换行符分隔下一组。

函数reshape将接受2个参数,即组的长度和要整形的字符串。它将忽略字符串中的空格,即

reshape(1,"AB CD") #returns A\nB\nC\nD
reshape(6, "AB CD SDSD SDSDSDSDSDSD") #returns ABCDSD\nSDSDSD\nSDSDSD\nSD

这是我当前的代码

def reshape(n, str):
    # remove space
    str = ''.join(str.split())
    lines = []
    buff = ''
    for ind,s in enumerate(str):
        # keep adding the buffer
        if len(buff) < n:
            buff += s
        else:
            # if the buffer length exceeds the max group length, add to the return list
            lines.append(buff)
            # reset the buffer
            buff = s

    return '\\n'.join(lines)

在我的职能中,答案总是会遗漏最后一组。逻辑有问题吗?

2 个答案:

答案 0 :(得分:1)

这可以使用迭代器更有效地解决。另外,不要调用变量str,它会覆盖内置的str

from itertools import zip_longest

def reshape(n, string):
    # remove space
    string = string.replace(' ', '')
    lines = (''.join(chars) for chars in zip_longest(*([iter(string)] * n), fillvalue=''))

    return '\n'.join(lines)

输出:

reshape(1,"AB CD")
'A\nB\nC\nD'

reshape(6, "AB CD SDSD SDSDSDSDSDSD")
'ABCDSD\nSDSDSD\nSDSDSD\nSD'

顺便说一句,它比公认的解决方案快4-5倍。

答案 1 :(得分:0)

问题在于,如果没有超过组的最大长度,您就不会在列表中输入最后一个缓冲区。

尝试在循环之后添加此内容:

if(buff):
    lines.append(buff)