Python:填充可变长度的字符串

时间:2014-10-15 12:40:09

标签: python list tuples string-length

我有一组可变长度的字符串,我正试图用列表中的文本填充。整个设置看起来应该是这样的:

输入:

list_of_string_lengths = [5, 8, 10]
list_of_words = ["this", "is", "some", "text"]

输出:

list_of_strings = ["this", "is some", "text"]

关于stackoverflow的另一个答案,我得到了这个片段:

def truncate(s_tuples, max_length):

    def stop_iterator(s_tuples):
        tot_len = 0
        for s,num in s_tuples:
            tot_len += get_words_number(s)
            if tot_len >= max_length:
                if tot_len == max_length:
                    yield s
                break
            yield s

    return ' '.join(stop_iterator(s_tuples))

for word in list_of_words:
    w_tuples.append(word, len(word))

使用

for length in list_of_lengths:
    wanted_string = truncate(w_tuples, length)
    list_of_strings.append(wanted_string)

我得到了正确长度的字符串,但它们显然总是从单词列表的开头开始。

我尝试添加

w_tuples = w_tuples[len(wanted_string.split()):]

到循环结束,但结果是:

list_of_strings = ["this is some text", "", ""]

我错过了什么?是否有另一种更好的方法来获得我想要的结果?

0 个答案:

没有答案