簡體   English   中英

ValueError:int() 的無效文字,基數為 10:'26.02.2018'

[英]ValueError: invalid literal for int() with base 10: '26.02.2018'

因此,當我收到此錯誤時,我很無聊並決定使用 Python 進行一些編碼(我是菜鳥):

Blockquote ValueError: 基數為 10 的 int() 的無效文字:'26.02.2018'

這是完整的腳本:

print("This is case sensitive!")

#Ask for the users name
name_1 = input("What is your name?")

#Ask for the users gender
gender = input("Are you a male, a female or other(If other, then what?)?")

#Ask for the users birthday
birthday = input("When were you born?(DD.MM.YYYY)")

#Ask for the users location
location = input("In what country do you live?")

import datetime
now = datetime.datetime.now()
today = now.strftime("%d.%m.%Y")

today = int(today)
birthday = int(birthday)

age = today - birthday

if gender == "male":
    print("Mr.", name_1)
    print(age)
    print (birthday )
    print("Male")
    if birthday == today:
        print("Happy Birthday,Mr.", name_1)
    else:
        ""

elif gender == "female":
    print ("female")

else:
    print (gender)
    print ("Part of the LGBT+ Community.")

此腳本不完整。

您正在嘗試將'26.02.2018'轉換為int ,這是不可能的(兩個小數點)。

使用datetime.strptime將其解析為DateTime對象:

from datetime import datetime as dt
# ...
birthday = dt.strptime(birthday, '%d.%m.%Y')

然后將它與今天作為DateTime對象進行比較,而不是將其轉換為int

您不能將 '26.02.2018' (日期)轉換為整數。 Python 不知道如何處理句點。 你可以這樣做

todayarray= today.split('.')

獲取包含第一個條目中的日期、第二個條目中的月份和第三個條目中的年份的數組。 然后,您可以類似地對生日做同樣的事情(因為當您修復它並使其到達該行時,這也會導致完全相同的錯誤),然后通過並行迭代兩個數組來對它們執行減法for 循環。 然后,您可以通過執行此操作將您返回的內容轉換回您想要的內容(我們假設您將結果數組稱為 resultarray)

result=resultarray[1]+"."+resultarray[2]+"."+resultarray[3]"

編輯:呃,我很抱歉不清楚,但是當你按照我的指示拆分時。 字符串中的值將能夠轉換為整數。 這就是您將如何實施此解決方案。

Edit2:我會盡可能清楚並輸入完整的解決方案

print("This is case sensitive!")

#Ask for the users name
name_1 = input("What is your name?")

#Ask for the users gender
gender = input("Are you a male, a female or other(If other, then what?)?")

#Ask for the users birthday
birthday = input("When were you born?(DD.MM.YYYY)")

#Ask for the users location
location = input("In what country do you live?")

import datetime
now = datetime.datetime.now()
today = now.strftime("%d.%m.%Y")

today = today.split('.')
birthday = birthday.split('.')
for x in range(0,3):
    age[x]=today[x]-birthday[x]
age = age[0]+"."+age[1]+"."+age[2]

if gender == "male":
    print("Mr.", name_1)
    print(age)
    print (birthday )
    print("Male")
    if birthday == today:
        print("Happy Birthday,Mr.", name_1)
    else:
        ""

elif gender == "female":
    print ("female")

else:
    print (gender)
    print ("Part of the LGBT+ Community.")

當然,這將保存年齡,即他們活着的天數、月數和年數,以句點分隔。 如果你想要另一種格式,它應該很容易實現。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM