Home > Mobile >  AttributeError: 'list' object has no attribute 'lower'. How to fix the code in o
AttributeError: 'list' object has no attribute 'lower'. How to fix the code in o

Time:11-28

`

def removeDigits(str):
    return str.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()
    if choice.upper() == 'UPPER':
        print(res.upper())
        
    elif choice.lower() == 'lower':
        print(res.lower())
    else:
        print('An error has occured')
    

fileinput()
AttributeError                            Traceback (most recent call last)
Input In [1], in <cell line: 23>()
     19     else:
     20         print('An error has occured')
---> 23 fileinput()

Input In [1], in fileinput()
     15     print(res.upper())
     17 elif choice.lower() == 'lower':
---> 18     print(res.lower())
     19 else:
     20     print('An error has occured')

AttributeError: 'list' object has no attribute 'lower'

`

I wanted the program to pull a string from a file and print it while removing the integers in that string, and then have the user choose whether they want upper or lower and convert the new string without the integers into either upper or lower.

The first section where it needs to pull from a text file and remove integers work, but I get an attribute error for converting the text to upper or lower.

CodePudding user response:

It is because you can't make a list lower or upper case. You have to make the elements in the list lower or upper case.

For example:

res_lower = [item.lower() for item in res]
print(res_lower)

Or in one line:

print([item.lower() for item in res])

Instead of:

print(res.lower())

If you want to print each element of the list individually, use a for loop:

for item in res:
    print(item.lower())

Good Luck!

  • Related