Python 从字符串列表中去除不需要的字符
我有一个名为Python 从字符串列表中去除不需要的字符,python,list,strip,Python,List,Strip,我有一个名为file\u contents的字符串列表。 列表中的每个项目都按以下格式的数字进行:#1#2.等 我想从列表中的每一项中删除它们 for item in range(len(file_contents)): file_contents[item].lstrip('#' + [item] + ". ") 所以,我想把“#1.Apples”变成“Apples” 有什么建议吗 当我运行此命令时,我得到以下错误: TypeError: Can't convert 'list' o
file\u contents
的字符串列表。
列表中的每个项目都按以下格式的数字进行:#1#2.等
我想从列表中的每一项中删除它们
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
你很适合这里:
import re
pattern = re.compile(r'#\d+\.\s*')
new_contents = [pattern.sub('', item) for item in file_contents]
我建议阅读doc链接,看看regex是如何工作的,但简单解释一下模式:
-查找#
字符#
-后跟一个或多个数字\d+
-然后是一个点字符\。
-然后是任意数量的空白\s*
re.sub
查找该模式,然后将其替换为'
,一个空字符串-从而将其切掉
您还严重误解了lstrip
和Python语法在一般情况下的工作原理:
[item]
只是[0]
,[1]
等等,这就是为什么不能将它连接到字符串。我不太清楚你想在那里实现什么李>
你很适合这里:
import re
pattern = re.compile(r'#\d+\.\s*')
new_contents = [pattern.sub('', item) for item in file_contents]
我建议阅读doc链接,看看regex是如何工作的,但简单解释一下模式:
-查找#
字符#
-后跟一个或多个数字\d+
-然后是一个点字符\。
-然后是任意数量的空白\s*
re.sub
查找该模式,然后将其替换为'
,一个空字符串-从而将其切掉
您还严重误解了lstrip
和Python语法在一般情况下的工作原理:
[item]
只是[0]
,[1]
等等,这就是为什么不能将它连接到字符串。我不太清楚你想在那里实现什么李>
我想你想做的是
stripped_contents = []
with open('test.data') as f:
for i, line in enumerate(f):
strip = '#' + str(i + 1) + ". "
stripped_line = line.lstrip(strip)
stripped_contents.append(stripped_line)
print stripped_contents
i、 e.您需要将项转换为字符串而不是列表。另外,因为它从0开始,所以您需要项目+1
另一个解决办法可能是
stripped_contents = []
with open('test.data') as f:
for i, line in enumerate(f):
start_pos = len('#' + str(i + 1) + ". ")
stripped_line = line[start_pos:]
stripped_contents.append(stripped_line)
print stripped_contents
正则表达式也可以工作。但是对于这样一个简单的问题,我觉得太复杂了。我想你想做的是
stripped_contents = []
with open('test.data') as f:
for i, line in enumerate(f):
strip = '#' + str(i + 1) + ". "
stripped_line = line.lstrip(strip)
stripped_contents.append(stripped_line)
print stripped_contents
i、 e.您需要将项转换为字符串而不是列表。另外,因为它从0开始,所以您需要项目+1
另一个解决办法可能是
stripped_contents = []
with open('test.data') as f:
for i, line in enumerate(f):
start_pos = len('#' + str(i + 1) + ". ")
stripped_line = line[start_pos:]
stripped_contents.append(stripped_line)
print stripped_contents
正则表达式也可以工作。但对于这样一个简单的问题,感觉太复杂了。如果您不想从左侧剥离,请将所有字符传递给lstrip:
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:
return (filename, "does not exist.")
with open(filename) as file:
file_contents = [line.lstrip("0123456789.").strip() for line in file]
您正在删除换行符,因此可以简单地调用strip,之后将删除换行符和前导空格:
In [14]: "#123. 1foo".lstrip("0123456789#.").strip()
Out[14]: '1foo'
如果您不想从左侧剥离,请将所有字符传递给lstrip:
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:
return (filename, "does not exist.")
with open(filename) as file:
file_contents = [line.lstrip("0123456789.").strip() for line in file]
您正在删除换行符,因此可以简单地调用strip,之后将删除换行符和前导空格:
In [14]: "#123. 1foo".lstrip("0123456789#.").strip()
Out[14]: '1foo'
如果你展示更多的代码,你会得到更好的答案。例如,变量名为
file\u contents
这一事实表明,您可以打开该文件并直接对其进行迭代,而范围(len(file\u contents))
反模式在这里肯定可以避免。我从另一个用户先前删除的评论中发现,我的问题是[item]我的lstrip()参数的一部分。如果显示更多代码,您会得到更好的答案。例如,变量名为file\u contents
这一事实表明,您可以打开该文件并直接对其进行迭代,而范围(len(file\u contents))
反模式在这里肯定可以避免。我从另一个用户先前删除的评论中发现,我的问题是[item]我的lstrip()参数的一部分。