2017-04-20 102 views
1

我有一个文件,我想得到行的长度。Python len()不好

但是,当我得到的长度:

8 10 11 9 9 30 11 12 11 10 10 8 8 26 13等等

有我的代码:

competition = [] 
with open('verseny.txt') as f: 
    competitor_number= int(next(f)) 
    for line in f: 
     shots = line.split() 
     competition.append(str(shots)) 

for num,shots in enumerate(competition, 1): 
    if '++' in shots: 
     print(num, end=",") 

print("\n") 

for shots in competition: 
    print(len(shots)) 

verseny.txt内容是:

21 
+--+ 
--+++- 
-+--+-- 
++--- 
-++-- 
--+-+++----------------+-+ 
+-++--+ 
-+-+++-+ 
-+--+-+ 
--+++- 
-+--+- 
++-- 
-+-- 
-++----------------+-+ 
+-++-+--+ 
-+-+++- 
-+--+-+- 
++---+ 
-++-+- 
--+-+++---+-------------+-+ 
+-++--+ 

回答

7

问题是str(line.split())你基本上将"+--+\n"转换成"['+--+']"(其长度为8)。

而不是line.split()你可能打算使用line.strip()

+0

这是解决方案! :D谢谢! – Giton22

+0

或'line.rstrip()'只能移除到右侧。 –

+0

@ Giton22如果这是解决方案,只需接受答案。 –

0
#Length of each lines appended in a list 
l=[] 
for f in open('verseny.txt'): 
    l.append(len(f)) 

print l 



#if you want number of line in this file 
count=-1 
for f in open('verseny.txt'): 
    count+=1 
print count