Cha*_*tte 3 python text character
我正在努力完成Python中给我的这项任务,它是关于修改给定文本文件中的文本(读取模式,而不是写入模式)。这是我的一段代码:
file = open("fileName")
suffix_list:[]
for e in file:
elements=e.split()
result=elements.endswith("a")
suffix_list.append(result)
Run Code Online (Sandbox Code Playgroud)
然后我想打印带有后缀的列表的长度:
print(len(suffix_list))
Run Code Online (Sandbox Code Playgroud)
相反,我收到此错误:“'list'对象没有属性'endswith'”我真的不确定这里出了什么问题,有人可以帮忙吗?
endswith使用字符串而不是列表进行检查。e.split()给出一个列表。遍历此列表并检查endswith列表中的每个项目。
suffix_list = []
for e in file:
for element in e.split():
if element.endswith("a"):
suffix_list.append(element)
print(len(suffix_list))
Run Code Online (Sandbox Code Playgroud)
另外,还有一个列表理解版本:
suffix_list = []
for e in file:
suffix_list.extend([element for element in e.split() if element.endswith('a')])
Run Code Online (Sandbox Code Playgroud)
假设您需要一个平面列表而不是列表列表。