2017-04-20 33 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