Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3 - Check letters in string with the next letter

If I have a string

String = 'ABCEEFGH'

How can I check what letter is beside each letter without going out of index?

for index in range(len(String)):
    if String[index] == String[index+1]: 
        print('Double')
like image 945
Torched90 Avatar asked Mar 17 '23 20:03

Torched90


1 Answers

You can use enumerate, slicing the string up to the second last character:

String = 'ABCEEFGH'

for ind,ch in enumerate(String[:-1]):
    if ch == String[ind+1]:
        print('Double')

In your own code the logic would be the same len(String)-1 but enumerate is the way to go:

for index in range(len(String)-1):
    if String[index] == String[index+1]:
        print('Double')

The fact you seen to only want to check if any two adjacent characters are identical, maybe using any would be best:

String = 'ABCEEFGH'

if any( ch == String[ind+1] for ind, ch in enumerate(String[:-1])):
        print('Double',ch)

any will short circuit and break the loop as soon the condition is Trueor else evaluate to False if we have no match.

like image 89
Padraic Cunningham Avatar answered Mar 20 '23 03:03

Padraic Cunningham