2013-02-09 55 views
1

這段代碼的目的是獲取一個字符串並以特定格式打印出來。例如,給定:帶格式的打印:布爾問題

s = "Hello" 

程序應該打印出來:

+---+---+---+---+---+ 
| H | e | l | l | o | 
+---+---+---+---+---+ 

如果字符串的大小比控制檯的柱尺寸更大,它則應該打印出字符串中這種格式:

+---+---+---+---+---+ 
| H | e | l | l | o | 
+---+---+---+---+---+ 
| H | e | l | l | o | 
+---+---+---+---+---+ 
| H | e | l | l | o | 
+---+---+---+---+---+ 
| H | e | l | l | o | 
+---+---+---+---+---+ 

不幸的是,第二個條件不起作用,我似乎無法弄清楚爲什麼。

這裏是我的代碼:

import os 

s = "Hello"*20 
(consoleRows,consoleCol)=os.popen('stty size','r').read().split() 
top = outer = "+---"*len(s)+'+'+'\n' 
for i in range(len(s)): 
    outer += "| "+s[i]+" " 

outer += '|\n' 
outer += top[:len(top)-1] 

split = outer.split('\n') 
if(len(split[0]) > consoleCol): #problem lies on this line. Even though the size of 
    outer = outer.split('\n') #split[0] is greater than consoleCol the if statement 
    beg = 0 #isn't entered.               
    size = consoleCol 
    print(outer[0][beg:size]) 
    while(size < len(outer[0])): 
     print(outer[1][beg:size]); 
     print(outer[2][beg:size]); 
     beg = size 
     size += size 
else: 
    print(outer) 

有人能看到我的問題是什麼?我打印出外部[0]和consoleCol的大小。 len(輸出[0])大於consoleCol。

+0

您可能想用'os.get_terminal_size()'替換對'os.popen()'的調用' – 2013-02-12 21:53:44

回答

2

代碼中的錯誤:consoleCol是一個字符串,而不是一個整數。

更換(consoleRows,consoleCol)=os.popen('stty size','r').read().split()(consoleRows,consoleCol)=map(int, os.popen('stty size','r').read().split())

這仍然沒有產生預期的結果 - 你必須自己弄清楚休息了,也許在這個過程中清理代碼。

2

首先,我不是蟒蛇小子。也就是說,我會建議將邏輯從佈局中分離出來。創建方法drawHorizontalLine,drawContentLine(Char[5])Char[5][] splitContent(String)。之後調試應該很容易。