Home > front end >  Index out of range when printing adjacent letter
Index out of range when printing adjacent letter

Time:11-14

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

CodePudding user response:

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)

CodePudding user response:

An easy pythonic approach is to use itertools.zip_longest:

from itertools import zip_longest

stg = 'AVBFGHJ'

for x in zip_longest(stg, stg[1:]):
    print(*x)

Without itertoools, you can handle the last case separately:

for x in zip(stg, stg[1:]):
    print(*x)
print(stg[-1], None)

Output:

A V
V B
B F
F G
G H
H J
J None
  • Related