Search code examples
pythonstringindices

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

Solution

  • 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.