2017-04-20 7 views
1

ファイルがあり、行の長さを取得したい。Python len()not good

しかし、私は長さを取得する場合:

:私のコードは、など

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