Pranav Sharma
Pranav Sharma

Reputation: 59

Why does the code given below gives the error "TypeError: string indices must be integers"?

the code gives error when i try to print the substring

def wrap(string, max_width):
    n=int(len(string)/max_width)
    i=0 
    j=max_width+1
    for _ in range(n):
        print(string[i,j])
        i=j
        j+=max_width

    print(string[i,len(string)])

Upvotes: 0

Views: 51

Answers (2)

flashy
flashy

Reputation: 564

This is the correct function

def wrap(string, max_width):
    n=int(len(string)/max_width)
    i=0 
    j=max_width+1
    for _ in range(n):
        print(string[i:j])
        i=j
        j+=max_width

    print(string[i:len(string)])

You get error because you can not take chars from a string with string[i,j] and string[i,len(string)]. In Python ":" is used to take chars from a string.

Upvotes: 0

Green Cloak Guy
Green Cloak Guy

Reputation: 24691

This:

string[i,j]

is invalid formatting. You can only put one argument when you're trying to get a particular index of a string, and that argument has to be an integer. So the problem here is that python is interpreting i,j as a tuple, not an integer.

You're probably trying to slice the string from index i to index j. In that case, the syntax is

string[i:j]

which works because : tells python that this is a slice, and to look for a separate index on the left and right side of the :.

Upvotes: 1

Related Questions