pythonpython-3.xlistfor-loopindexoutofrangeexception

Index out of range when printing adjacent letter


I have string which is as follows below

stg = 'AVBFGHJ'

I want the adjacent letter to be printed as expected below

AV

VB

BF

FG

GH

HJ

J None

I tried below code but throws me error like Index out of Range

My code :

for i in range(len(stg)):
    print(stg[i],stg[i+1])


Solution

  • This is meant to happen. You are accessing an index that is out of the range of the string.

    If you really want to do it this way however, you can do something like this

    stg = 'AVBFGHJ'
    for i in range(len(stg)):
        if (i + 1) < len(stg):
            print(stg[i],stg[i+1])
        else:
            print(stg[i], None)