首页 > 解决方案 > 不支持的操作数类型,但找不到错误

问题描述

我正在尝试创建一个脚本,该脚本在文本文件中组装回文列表,其中单词由中断分隔:

def modified_palindromes(filename):
   """Returns a list of all words that spell the same backwards after moving the first letter to the end,as found in the file with the given name."""
    result = []
    
    with open(filename, 'r') as f:
        for line in f:
             for i in range(len(line.lower())):
                if line.lower()[i:(i+1)] == line.lower()[(len(line.lower())-i-1):len(line.lower()-i)]:
                    result.append(line)    
    return result

    pass  # TODO

但是,我在检查从左侧算起的第 i 个字母是否等于从右侧算起的第 i 个字母的行中出现错误。这是错误:

if line.lower()[i:(i+1)] == line.lower()[(len(line.lower())-i-1):(len(line.lower()-i))]:
TypeError: unsupported operand type(s) for -: 'str' and 'int'

所以我猜想在这个 if 语句中的某个地方,我正在从字符串中扣除一个 int,反之亦然,但我似乎找不到在哪里。Len() 应该返回一个 int,i 是一个 int,1 是一个 int,那么它哪里出错了?

标签: python

解决方案


是的,你是。这里(line.lower()-i)


推荐阅读