[英]Remove whitespaces from beginning and end of each line in a file in python
我试图从文件中读取一些数字并将它们存储到一个名为numbers
的数组中。 我为每行使用strip()
来删除每行末尾的\\n
。 我还为每一行使用split(' ')
来删除数字之间的空格。
问题是在输入文件中,行上的第一个字符和行上的最后一个字符是空格。 我怎么擦掉它们?
这是我的代码:
def read_from_file():
f = open('input_file.txt')
numbers = []
for eachLine in f:
line = eachLine.strip()
for x in eachLine.split(' '):
line2 = int(x)
numbers.append(line2)
f.close()
print numbers
这是文本文件,下划线是空格:
_9 5_
_2 3 1 5 4_
_2 1 5_
_1 1_
_2 1 2_
_2 2 3_
_2 3 4_
_3 3 4 5_
_2 4 5_
_2 1 5_
_3 1 2 5_
strip()
已经从两端删除了空格。 错误在于:
for x in eachLine.split(' '):
你应该在for
使用line
而不是eachLine
。
为了避免这种问题,你可以避免使用中间变量:
for line in f:
for x in line.strip().split():
# do stuff
请注意,调用不带参数的split()
在任何空格序列上进行拆分,这通常是您想要的。 看到:
>>> 'a b c d'.split()
['a', 'b', 'c', 'd']
>>> 'a b c d'.split(' ')
['a', '', 'b', 'c', 'd']
注意最后一个结果的空字符串。 split(' ')
分割在每个单个空格。
with open("myfile.txt") as lines:
for line in lines:
print line.strip()
使用.strip
删除前导和尾随空格
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.