You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AttributeError问题:列表对象无lower属性,如何修复大小写转换代码?

问题修复:列表对象无法调用字符串大小写转换方法

错误原因

AttributeError的核心问题是:变量res是列表(list)类型,而upper()/lower()是字符串(str)专属的方法,列表没有这些属性。你通过list(map(removeDigits, lines))生成的res,是把文件每行处理后存入列表的结果,直接对整个列表调用字符串方法必然报错。

修复方案

根据需求选择以下两种修复方式:

方案1:将处理后的内容合并为单个字符串处理

适合把文件内容当作一个整体文本的场景,先合并所有行,再统一转换大小写:

def removeDigits(s):
    # 避免使用内置类型名str作为参数名
    return s.translate({ord(i): None for i in '0123456789'})

def fileinput():
    with open('constant.txt') as f:
        lines = f.readlines()
    
    print('Initial string: ', lines)
    # 处理每行并去除换行符,再合并为单个字符串
    processed_lines = [removeDigits(line).strip() for line in lines]
    res = ' '.join(processed_lines)
    print('Final string: ', res)
    
    print('Make string upper or lower?')
    choice = input().strip()
    if choice.upper() == 'UPPER':
        print(res.upper())
    elif choice.lower() == 'lower':
        print(res.lower())
    else:
        print('Invalid choice')

fileinput()

方案2:保留列表结构,逐个转换每行的大小写

适合需要保留文件行结构的场景,遍历列表对每个字符串元素单独处理:

def removeDigits(s):
    return s.translate({ord(i): None for i in '0123456789'})

def fileinput():
    with open('constant.txt') as f:
        lines = f.readlines()
    
    print('Initial string: ', lines)
    res = list(map(removeDigits, lines))
    print('Final string: ', res)
    
    print('Make string upper or lower?')
    choice = input().strip()
    if choice.upper() == 'UPPER':
        for line in res:
            print(line.upper())
    elif choice.lower() == 'lower':
        for line in res:
            print(line.lower())
    else:
        print('Invalid choice')

fileinput()

内容的提问来源于stack exchange,提问作者Rasal.A

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 03:30:54