Reputation: 19
I'm not sure what I'm doing wrong here, spent all day googling and reading python books..
I have the following function:
def extract(inNo, inputFile2, outputFile):
ifile = open(inputFile2, 'r')
ofile = open(outputFile, 'w')
lines = ifile.readlines()
for line in lines:
print(str(len(line)))
if str(len(line)) == str(inNo):
ofile.write(line)
I'm trying to understand len()
, I seem to get odd results when using it.
My input file is the following:
1
22
333
4444
55555
666666
7777777
88888888
Now if I use '7' as the inNo
variable, the output (i.e., print
) I get is:
2
3
4
5
6
7
8
8
and the output file becomes:
666666
I'm sure from checking in python.exe length count start from 1 i.e:
len('123')
would give a result of
3
Is my understanding of len()
wrong, or am I coding it wrong?
Essentially, what this function does is; it takes an input, an output and a character length as arguments. These come from a different function and the 2nd function calls this one with arguments.
This function reads lines from the input file. For every line, it gets the character length and compares it to the input No. If they are equal it should write that line to the output file. I assume as I have no "else:" it should carry on the iteration. The print() function allows me to see exactly what it has calculated as the length.
When I try to add '- 1' or '+ 1' to the len() i.e. (len(line) + 1) it causes even more odd things start to happen.
Upvotes: 0
Views: 1746
Reputation: 156
len()
also considers the new line character \n
, that's why you're getting one more in every line except the last one.
Upvotes: 4