2014-12-13 102 views
0

我試圖讓我的輸入是這樣的,但我不知道我應該怎麼格式化:Python的輸入格式

Enter the rainfall for January: 1 
Enter the rainfall for February: 2 
Enter the rainfall for March: 3 

這是inputt我得到:

Enter the rainfall for January: 1 
Enter the rainfall for February: 2 
Enter the rainfall for March: 3 

這裏我的代碼:

def main(): 
months=("January","February","March","April","May","June","July","August","September","October","November","December") 
values=[0]*12 

for n in range(len(values)): 
    print("Enter the rainfall for", (months[n]), end=": ") 
    values[n]=float(input()) 

main() 

回答

1

進行打印語句

print("Enter the rainfall for", '{0:11s}'.format(months[n]+':'), end="") 

輸出

Enter the rainfall for January: 1 
Enter the rainfall for February: 2 
Enter the rainfall for March:  3 
Enter the rainfall for April:  4 
Enter the rainfall for May:  5 
Enter the rainfall for June:  6 
Enter the rainfall for July:  7 
Enter the rainfall for August: 8 
Enter the rainfall for September: 9 
Enter the rainfall for October: 0 
Enter the rainfall for November: 1 
Enter the rainfall for December: 2 
+1

只是要清楚這裏節省一些打字,它的工作,因爲我們知道所有月份的長度。在一般情況下,我們將找到字符串的最大長度,然後使用s.ljust(max_len)之類的東西來執行填充。 – user3820547 2014-12-13 19:28:33

0

您還可以通過使用現有calendar module

from calendar import month_name 
def main(): 
    values = [] 
    for month in month_name[1:]: 
     values.append(float(input('Enter the rainfall for {0:11s}'.format(month + ':'))))