2011-06-10 202 views
1

我在將字符串添加到另一個字符串時遇到問題。我是Python的新手。將字符串添加到字符串

該字符串不記得我添加的以前的值。

任何人都可以幫助我?以下是Python中的代碼片段。

我的問題是加密的,而環()。

感謝提前。

class Cipher: 


    def __init__(self): 
     self.alphabet = "abcdefghijklmnopqrstuvwxyz1234567890 " 
     self.mixedalpha = "" 
     self.finmix = "" 

    def encrypt(self, plaintext, pw): 
     keyLength = len(pw) 
     alphabetLength = len(self.alphabet) 
     ciphertext = "" 

     if len(self.mixedalpha) != len(self.alphabet): 
      #print 'in while loop' 

      x = 0 
      **while x < len(self.alphabet): 
       mixed = self.mixedalpha.__add__(pw) 
       if mixed.__contains__(self.alphabet[x]): 
        print 'already in mixedalpha' 
       else: 
        add = mixed.__add__(str(self.alphabet[x])) 
        lastIndex = len(add)-1 
        fin = add[lastIndex] 
        print 'fin: ', fin 
        self.finmix.__add__(fin) 
        print 'self.finmix: ', self.finmix 
       x+=1** 


     print 'self.finmix: ', self.finmix 
     print 'self.mixedalpha: ', self.mixedalpha 
     for pi in range(len(plaintext)): 
      #looks for the letter of plaintext that matches the alphabet, ex: n is 13 
      a = self.alphabet.index(plaintext[pi]) 
      #print 'a: ',a 
      b = pi % keyLength 
      #print 'b: ',b 
      #looks for the letter of pw that matches the alphabet, ex: e is 4 
      c = self.alphabet.index(pw[b]) 
      #print 'c: ',c 
      d = (a+c) % alphabetLength 
      #print 'd: ',d 
      ciphertext += self.alphabet[d] 
      #print 'self.alphabet[d]: ', self.alphabet[d] 
     return ciphertext 
+0

err ...你指出你認爲問題出在哪裏的任何機會?或者發佈一個更小的例子......或者至少發佈程序的輸出和期望輸出 – 2011-06-10 06:16:58

+0

請注意,添加兩個字符串是一個相當昂貴的操作,因爲它涉及創建一個新的字符串對象並複製這兩個字符串的內容串入它。如果你做了很多這些操作並且速度有一些重要性,可以考慮使用cStringIO模塊中的[StringIO](http://docs.python.org/library/stringio.html)對象。 – 2011-06-10 09:42:29

回答

0

我猜,但以下幾點:

self.finmix.__add__(fin) 

#should be 
self.finmix = self.finmix.__add__(fin) 
3

Python中的字符串是不可改變的,所以你應該重新分配變量名一個新的字符串。

功能與「__」在他們一般都不會你真的想用什麼。讓解釋器通過使用內置的運算符/函數(在本例中爲「+」運算符)爲您打電話。

因此,而不是:

self.finmix.__add__(fin) 

我建議你試試:

self.finmix = self.finmix + fin 

或同等及更簡潔:

self.finmix += fin 

如果你把這種整個的變化,你的問題可能會消失。

1

我沒有解決你的問題,但我有一對夫婦的更多一般性建議。

  • 的私有方法.__add__.__contains__並不意味着可以直接使用。您應該直接使用+in運算符。

  • 而是通過self.alphabet while循環的指標去的......

    while x < len(self.alphabet): 
        print self.alphabet[x] 
        x += 1 
    

    你可以只遍歷字母

    for letter in self.alphabet: 
        print letter 
    
  • class Cipher:觸發一種向後兼容的模式不適用於某些較新的功能。指定class Cipher(object):會更好。