`
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'
`
我想让程序从文件中提取一个字符串并打印出来,同时删除该字符串中的整数,然后让用户选择是要上限还是下限,并将没有整数的新字符串转换为上限还是下限。
第一部分需要从文本文件中提取并删除整数,但我在将文本转换为大写或小写时遇到了属性错误。
这是因为不能使列表大小写。您必须使列表中的元素小写或大写。
例如:
res_lower = [item.lower() for item in res]
print(res_lower)
或者在一行中:
print([item.lower() for item in res])
代替:
print(res.lower())
如果您想单独打印列表中的每个元素,请使用for循环:
for item in res:
print(item.lower())
祝你好运!