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

Viewed 59

I'm not exactly the kind of guy you call "good" at coding. In this particular scenario, on line 13, I'm trying to pop the first word in the list until I'm done, but it keeps giving me the 'str' object can not be interpreted as an integer issue.

What am I doing wrong here?

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
2 Answers

You could try splitting the string on the index, and inserting a newline there. Each time you do this your string gets one character longer, so we can use enumerate (which starts counting at zero) to add a number to our slice indexes.

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)

Output

Thanks 
for 
helping 
me

According your comments, this program will split lines to contain max K characters:

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

Prints:

hello my
name is
Bessie
and this
is my
essay
Related