我该如何修复这个在 list/string 中弹出单词的错误? (Python 3.x)

How can I fix this error for popping a word in a list/string? (Python 3.x)

我并不是您所说的那种擅长编码的人。在这种特殊情况下,在第 13 行,我试图弹出列表中的第一个单词,直到完成,但它一直给我 'str' object cannot be interpreted as an integer 问题。

我做错了什么?

n = n.split(" ")
N = n[0]
K = n[1]
f1 = input()
f1 = f1.split(" ")
f1 = list(f1)
current = 0
for x in f1:
    while current <= 7:
        print(x)
        f1 = list(f1.pop()[0])
        current = current + len(x)
        if current > 7:
            print("\n")
            current = 0

您可以尝试在索引处拆分字符串,然后在其中插入一个换行符。每次执行此操作时,字符串都会变长一个字符,因此我们可以使用枚举(从零开始计数)向我们的切片索引添加一个数字。

s = 'Thanks for helping me'

new_line_index = [7,11, 19]

for i, x in enumerate(new_line_index):
    s = s[:x+i] + '\n' + s[x+i:]
    
print(s)

输出

Thanks 
for 
helping 
me

根据您的意见,此程序将拆分行以包含最多 K 个字符:

K = 7
s = "hello my name is Bessie and this is my essay"

out, cnt = [], 0
for word in s.split():
    l = len(word)
    if cnt + l <= K:
        cnt += l
        if not out:
            out.append([word])
        else:
            out[-1].append(word)
    else:
        cnt = l
        out.append([word])

print("\n".join(" ".join(line) for line in out))

打印:

hello my
name is
Bessie
and this
is my
essay