Index out of range when printing adjacent letter

75 Views Asked by At

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

2

There are 2 best solutions below

0
jspoh On BEST ANSWER

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)
6
mozway On

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)

With python ≥3.10, you can use itertools.pairwise:

print(*(f"{a}{b}" for a,b in itertools.pairwise(stg)), sep='\n')

Thanks @chrslg for the remark.

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