我必須編寫一個程序,它依次獲取由哨兵DONE終止的多個字符串,然後將這個字符串列表右對齊地打印到最大字符串的長度。這裏是我的代碼:if語句不在while循環中執行
user = input("Enter strings (end with DONE):\n")
totalString = ""
while True:
if user.lower() == 'done':
break
else:
totalString = totalString + user + " "
user = input("")
lst = totalString.split(" ")
max = 0
for i in range(len(lst)):
if len(lst[i]) > max:
max = len(lst[i])
for i in range(len(lst)):
print("{:>{derp}}".format(lst[i],derp=max))
我遇到的問題是while循環中的if語句永遠不會執行,所以它只是卡在該循環中。
嘗試'while'循環之前打印user'的'的價值,因爲它可能有一個'\ N'在它的結束。使用'user = user.strip()'來解決這個問題。它在我的系統上正常工作。 – 2013-04-23 15:45:53
我已經添加了python3x標籤,因爲你使用'input()'從用戶獲取字符串。 – 2013-04-23 15:49:03
@AshwiniChaudhary那是怎麼回事?在'2.X'中存在['input()'](http://docs.python.org/2/library/functions.html#input)...哦,它是print()。沒關係。 – thegrinner 2013-04-23 15:50:38