简体   繁体   中英

Python - Readline and compare

Im trying to create a function which reads each line in a file and compares the words with their reverse (palindrome) version ie > (heheh = heheh) & (law = wal) . So when i tried to do that the condition has failed and the function returned an empty list.

CODE

def palindrome_lst():
    lst = []
    with open("words.txt", "r") as f:
        for line in f:
            if line == line[::-1]:
                lst.append(line)
    return lst

print palindrome_lst()

When iterating over the lines in a file, you're getting the line-terminator along with the rest of the line. Id est, you're not comparing "eye" == "eye" , but "eye\\n" == "\\neye" , which is of course false for all words.

Try adding line = line.strip() before the comparison.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM