2017-02-21 89 views
0

我有一個在Python中循環,並在字符串中跳過的最後一個字符,我想輸出變量,像這樣: for i in "125": print (i) 和它沒有打印5,這裏是我的腳本:跳過一個字符?

OctalBinary1 = { 
      "0" : "000", 
      "1" : "001", 
      "2" : "010", 
      "3" : "011", 
      "4" : "100", 
      "5" : "101", 
      "6" : "110", 
      "7" : "111" 
} 
def toBinaryOctal(x): 
      counter = 0 
      sum_var = "" 
      fin_var = "" 
      for i in x: 
        counter += 1 
        sum_var += str(i) 
        if (counter != 3): 
           for x , y in OctalBinary1.items(): 
             if x == sum_var: 

                fin_var += OctalBinary1[x] 
                sum_var = "" 
             else: 
              print ("Did not find a match") 
              print (i) 

      return fin_var 




print (toBinaryOctal("125")) 
+0

bin(125)'有什麼問題? –

+0

我只是試圖自己做 – guy

+0

作爲我的學校功課 – guy

回答

1
for i in x: 
    counter += 1 
    sum_var += str(i) 

    if (counter != 3): 

當for循環到達"5"計數器將在3行if (counter != 3),所以它會打破後面的循環。這就是爲什麼你沒有得到"5"輸出。

+0

哦對了!謝謝!這是一個愚蠢的錯誤 – guy