我有一個問題,我在樹莓派終端遇到。花時間作爲HHMM格式的用戶輸入
>>> alarm = input('Please input the time for the alarm in format HHMM: \n ')
>>> print(alarm)
我輸入0700,然後按ENTER鍵,但它打印出448,而不是0700 當我試圖在空閒時,其推出的0700爲什麼不是在樹莓派終端推出0700?我怎樣才能讓終端把0700拿出來?
我有一個問題,我在樹莓派終端遇到。花時間作爲HHMM格式的用戶輸入
>>> alarm = input('Please input the time for the alarm in format HHMM: \n ')
>>> print(alarm)
我輸入0700,然後按ENTER鍵,但它打印出448,而不是0700 當我試圖在空閒時,其推出的0700爲什麼不是在樹莓派終端推出0700?我怎樣才能讓終端把0700拿出來?
輸入()函數將您的輸入,並將其轉換爲字符串。
0070被認爲是一個八進制數。它首先轉換爲十進制數字,然後轉換爲字符串。
print str(0070)
>>> 56
import time
alarm = str(raw_input('Please input the time for the alarm in format HHMM: \n '))
print alarm
>>> Input: 0080
>>> Output: 0080
您應驗證用戶輸入的時間。例如,你不能輸入一個時間像4012 可以使用日期時間模塊如下驗證時間:
import datetime
try:
a = datetime.datetime.strptime(raw_input('specify time in HHMM format: '), "%H%M")
print a.strftime("%H%M")
except:
print "Please enter correct time in HHMM format"
有使用DateTime對象的其他優點。你可以在你的時間執行各種操作。例如。添加時間,從中減去時間,將其轉換爲各種格式等。 瞭解詳細信息:https://docs.python.org/2/library/datetime.html
您沒有告訴他如何修復它 – Will
問題是,您正在使用input()
而不是raw_input()
。
raw_input()
消失在Python 3
爲了解決您的問題,
變化alarm = input('Please input the time for the alarm in format HHMM: \n ')
到alarm = raw_input('Please input the time for the alarm in format HHMM: \n ')
好但有點explantion的:
raw_input()
需要用戶輸入的內容並將其作爲st環。
input()
先取raw_input()
,然後再對其執行eval()
。
所以,如果你(在Python 2)eval(str(0700)
這樣做,它會返回448
顯然我已經導入了必要的... – Mayor
您正在使用不同版本的python。 http://stackoverflow.com/questions/4915361/whats-the-difference-between-raw-input-and-input-in-python3-x – itdoesntwork
如果它是一個字符串,你可以打印0700。如果您將0700投射到一個int,則前面的零將消失 – MYGz