python - 不支持的操作数类型,但找不到错误
问题描述
我正在尝试创建一个脚本,该脚本在文本文件中组装回文列表,其中单词由中断分隔:
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,那么它哪里出错了?
解决方案
是的,你是。这里(line.lower()-i)
推荐阅读
- arrays - 指向从 char[13] 分配给 char 的整数转换的不兼容指针
- c++ - 如何使用正则表达式在 C++ 中删除一行文本
- xml - 如何使用新元素扩展第二个 xsd 架构
- wordpress - Wordpress 网站上的数据库错误“一个或多个数据库表不可用”
- azure - Azure Key Vault 机密查询
- spring-integration - Spring集成DelayHandler、retryDelay和messageStore
- java - SOAP - 只保留父/根命名空间
- wpf - 在 Xamarin WPF 中更改汉堡按钮的属性
- r - 有没有办法将共享相同 ID 的列值分隔到 R 中的单独列中?
- java - 如何从 html 源中解析出 imgs 标签的 src 属性值