【发布时间】:2017-07-17 13:59:02
【问题描述】:
我有以下代码,它在从文件读取时成功去除了行尾字符,但对于任何前导和尾随空格都没有这样做(我希望保留它们之间的空格!)
实现这一目标的最佳方法是什么? (注意,这是一个具体的例子,所以不是一般的字符串剥离方法的重复)
我的代码:(尝试使用测试数据:“Mr Moose”(未找到)如果您尝试 “Mr Moose”(即 Moose 后面的空格)会起作用。
#A COMMON ERROR is leaving in blank spaces and then finding you cannot work with the data in the way you want!
"""Try the following program with the input: Mr Moose
...it doesn't work..........
but if you try "Mr Moose " (that is a space after Moose..."), it will work!
So how to remove both new lines AND leading and trailing spaces when reading from a file into a list. Note, the middle spaces between words must remain?
"""
alldata=[]
col_num=0
teacher_names=[]
delimiter=":"
with open("teacherbook.txt") as f:
for line in f.readlines():
alldata.append((line.strip()))
print(alldata)
print()
print()
for x in alldata:
teacher_names.append(x.split(delimiter)[col_num])
teacher=input("Enter teacher you are looking for:")
if teacher in teacher_names:
print("found")
else:
print("No")
期望的输出,关于生成列表 alldata
['Mr Moose:Maths', 'Mr Goose:History', 'Mrs Congenelipilling:English']
即 - 删除开头、分隔符之前或之后的所有前导和尾随空格。必须留下诸如 Mr Moose 等单词之间的空格。
教科书内容:
Mr Moose : Maths
Mr Goose: History
Mrs Congenelipilling: English
提前致谢
【问题讨论】:
-
teacher_names.append(x.split(delimiter)[col_num].strip())是你想要的吗? -
用我上面编辑的代码再试一次(我之前的括号错了)
-
teacherbook.txt的内容是什么? -
@Chris_Rands - 完美。是的,这会起作用,但作为解决方案,我所追求的是将它从文件中读入 all_data 而不 /n 以及前导和尾随空格,而不是在之后处理它 - 我认为这将是更好的解决方案
-
@MissComputing:由于只有在分隔符拆分后才能确定哪些字符实际上是前导/尾随空格,所以我认为 Chris_Rands 的答案与您将得到的一样接近。