Python – How to compare strings to ensure they do not contain a double character, then save them to a file

Question:

I am trying to make it so that if there are 2 words that have double letters in the loop, it will simply pass over them, or vice versa.

def initalizeData():
    try:
        words = open('words.txt', 'r')
    except FileNotFoundError:
        print("Check the file name or path.")
    else:
        list = open('final.txt', 'a')
        scriptwords = words.readlines()
        for w in scriptwords[:]:
            if len(w) >= 3 and len(w) <= 6:
                if w[:1] == 'a' or w[:1] == 'p':
                        for letter in scriptwords:
                           #this is where the statement should go, below is my attempt at it. 
                           #if scriptwords[letter] != scriptwords[(letter+1)]:
                                list.write(w.upper())
                        list.close()

I have tried the above, and the result is that Replit says:

File "main.py", line 14, in initalizeData
    if scriptwords[letter] != scriptwords[(letter+1)]:
TypeError: list indices must be integers or slices, not str
Asked By: Alex

||

Answers:

You can iterate through the letters of the word using the pattern below. This will check that all pairs of letters are different in the word. And I also changed the file name to word_list to avoid the name collision with list.

def initalizeData():
    try:
        words = open('words.txt', 'r')
    except FileNotFoundError:
        print("Check the file name or path.")
    else:
        word_list = open('final.txt', 'a')
        scriptwords = words.readlines()
        for w in scriptwords:
            if len(w) >= 3 and len(w) <= 6:
                if w[:1] == 'a' or w[:1] == 'p':
                        if all(l1 != l2 for l1,l2 in zip(w,w[1:])):
                            word_list.write(w.upper())
        word_list.close()
Answered By: bn_ln
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.