【发布时间】:2016-03-08 06:31:48
【问题描述】:
我有一个名为file_contents 的字符串列表。
列表中的每个项目都以这种格式的数字开头:#1。 #2。 ETC..
我想从列表中的每个项目中删除它们。
for item in range(len(file_contents)):
file_contents[item].lstrip('#' + [item] + ". ")
所以,我想把"#1. Apples" 变成"Apples"。
有什么建议吗?
当我运行它时,我收到以下错误:
TypeError: Can't convert 'list' object to str implicitly
这是我定义的整个方法:
def read_from_file(self, filename):
"""Checks if file exists, if it does, reads it in and creates new List object."""
file_contents = []
fileExists = os.path.isfile(filename)
if not fileExists:
print(filename, "does not exist.")
else:
with open(filename) as file:
file_contents = [line.strip() for line in file]
for item in range(len(file_contents)):
file_contents[item] = file_contents[item].lstrip('#' + str(item) + ". ")
list_name = file_contents[0]
list_contents = []
for item in file_contents:
if item in list_name:
continue
else:
list_contents.append(item)
new_list = List(list_name)
new_list.contents = list_contents
return new_list
【问题讨论】:
-
如果您显示更多代码,您会得到更好的答案。例如,您的变量名称为
file_contents的事实表明您可以打开文件并直接对其进行迭代,这里绝对可以避免使用range(len(file_contents))反模式。 -
我从另一个用户之前删除的评论中发现我的问题与我的 lstrip() 参数的 [item] 部分有关。