IndexError despite the the index being at 0?

Question:

I am creating a function which would format the string in a way that there will be a certain number of characters per line. So far I have this:

text = 'View and edit your personal , contact and card info jgfghv skjfdh'

#calculate number of lines needed 
if len(text) % 20 == 0: 
   lines = len(text) // 20 
else: 
   #add 1 for the remaining words 
   lines = len(text) // 20 + 1 

formatted = '' 

#create a list containing only the words in the text
words = text.split() 
#keeps track of where the function is in the string
word = 0
#keeps track of the character count of each line
limit = 0 


for i in range (1, lines):
   print('line: ' + str(i))  
   while limit <= 20:
      formatted += words[word] + ' ' 
      word += 1 
      limit += len(words[word])
   #reset limit for the next iteration
   limit = 0 
   #add a new line break at the end of this line
   formatted += 'n'

print(formatted)

However, an index error pops up at ‘words[word]’ saying that the index is out of range, even though it is at 0.Why does it cause this?

Asked By: rjrj

||

Answers:

I think you’ve come to realize the IndexError now (based on earlier comments), and may have idea how to address it.

Alternatively, if you could try the textwrap as earlier suggestion. It will be be much more simpler and concise: (Inspire by & Credit to @Samwise!)

import textwrap

text = 'View and edit your personal, contact and card info jgfghv skjfdh'

# reduced to just 2-3 lines now.
# *calculate number of lines* - no need any more.

# wrap the text to a width of 20 characters per line
wrapped = textwrap.wrap(text, width=20)

# combine the wrapped lines with newline words
formatted = 'n'.join(wrapped)

print(formatted)              

Output:

View and edit your
personal, contact
and card info jgfghv
skjfdh


```py
# if text is different:
text = "The quick brown fox jumps over the lazy dog. And the lazy dog cannot escape the final destiny."

Output:

The quick brown fox
jumps over the lazy
dog. And the lazy
dog cannot escape
the final destiny.
Answered By: Daniel Hao
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.