2012-04-09 7 views
1
def findLongRepeats(strToSearch): 
"""Search strTosearch to find the first location of longest repeated string 
of a single digit e.g '1111'. Do this for each digit from 0 to 9""" 
numbers = ['0','1','2','3','4','5','6','7','8','9'] 
for number in numbers: #reads a number line one at time 
    number_count = 0 #sets the count to 0 
    number = int(number) 
    longrepeats = [] #creates a new list 
    for x in strToSearch: #reads each digit one by one 
     if x == number: #if x is true it will add 1 to the number count 
      number_count += 1 
     if x != number: # if x is not flase it will add number count into the long repeat list 
      longrepeats.append(number_count) 
      number_count = 0 
    print "Found", max(longrepeats), number+'\'s in a row at character position', strToSearch.index(number*max(longrepeats)) 

def main(): 
    """DocT""" 
    File = open("pidigits.txt","rU") #opens file for reading 
    Thousand_String = 0 
    strLine ='' 
    for line in File: #reads each line 
     line = line.strip() 
     if '3.' in line: 
      line = line.replace('3.','') 
     Thousand_String += len(line) 
     strLine += str(line) 
     #print line 
    #File.close() 



    print 
    print "Number of pi digits to process:",Thousand_String 
    print 
    findLongRepeats(strLine) 
    print line 
main() 

」にしよう - このエラーを取得:はTypeError:+のためのサポートされていないオペランドのタイプ(S): 'int型' と 'str' は私が機能findLong繰り返しを実行すると '印刷'

File "PA5_.py", line 53, in main 
    findLongRepeats(strLine) 
    **File "PA5_.py", line 18, in findLongRepeats 
    print "Found", max(longrepeats), number+'\'s in a row at character position', strToSearch.index(number*max(longrepeats)) 
TypeError: unsupported operand type(s) for +: 'int' and 'str' 

私はエラーを修正する方法を見つけ出すことはできません助けてください

答えて

2

あなたは数numberに文字列('\'s in a row at character position')を追加することはできません文字列に数値を補間するための適切な方法がstring formattingないオプションを使用することです。。:

print "Found {0} {1}'s in a row at character position {3}".format(max(longrepeats), number, strToSearch.index(number * max(longrepeats))) 
+0

OPが実際に数値をintにしたいのであれば、これははるかに良い答えですが、最初はintへのキャストが不要であることを確信しています。つまり、int型にキャストしなくても、いいフォーマットが良いでしょう。 –

+0

@NolenRoyaltyそうです。文字列を文字列に補間したいとしても、文字列の書式設定を使用する必要があります。 – agf

+0

速い返信をありがとう、私はそれを試してみます。私は出力を投稿したので、このコードが生成すると思われるものをよりよく理解することができます。 –

関連する問題