I am trying to read some numbers from a file and store them into an array called numbers
.
I use strip()
for each line to remove the \n
at the end of each line. I also use split(' ')
for each line to remove the spaces between the numbers.
The problem is that in the input file the first character on the line and the last character on the line are spaces. How can I erase them?
This is my code:
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
This is the text file, where the underscores are spaces:
_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_
Use the . strip() method to remove whitespace and characters from the beginning and the end of a string. Use the . lstrip() method to remove whitespace and characters only from the beginning of a string.
The trim() function removes whitespace and other predefined characters from both sides of a string.
Answer : trim. trim function is ussed to remove strip whitespace (or other character) from beginning and end of the string.
s/[[:space:]]//g; – as before, the s command removes all whitespace from the text in the current pattern space.
strip()
already removes the spaces from both ends. The error is in the line:
for x in eachLine.split(' '):
You should use line
and not eachLine
in the for
.
To avoid this kind of problems you could avoid using the intermediate variable at all:
for line in f:
for x in line.strip().split():
# do stuff
Note that calling split()
without arguments splits on any sequence of whitespace, which is usually what you want. See:
>>> 'a b c d'.split()
['a', 'b', 'c', 'd']
>>> 'a b c d'.split(' ')
['a', '', 'b', 'c', 'd']
Note the empty string of the last result. split(' ')
splits on every single whitespace.
with open("myfile.txt") as lines:
for line in lines:
print line.strip()
Use .strip
to remove leading and trailing whitespace
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With