Home > database >  What's the command for making a string into a whole number?
What's the command for making a string into a whole number?

Time:03-20

print("DOB:")
Year = int(input("Year?"))
Month = int(input("Month?"))
Date = int(input("Date?"))
Birth_Year = 2022 - Year   Month   Date
January = 1
February = 2
March = 3
April = 4
May = 5
June = 6
July = 7
August = 8
September = 9
October = 10
November = 11
December = 12
print("Your DOB is..."   Birth_Year   "!")

It should be saying my birth year, but instead it is saying

Traceback (most recent call last):
  File "C:\Users\student\PycharmProjects\pythonProject1\app.py", line 3, in <module>
    Month = int(input("Month?"))
ValueError: invalid literal for int() with base 10: 'December'

First of all, yes I am on a student account. Second, I just want the title to be answered.

CodePudding user response:

If you want to map a string to a related integer, you need a domain-specific function. In the case of months, you should use datetime.datetime.strptime

m = datetime.datetime.strptime("December", "%B").month

int only turns a string that looks like an integer literal into an integer.


You also need to go in the reverse direction, if you want to turn Birth_Year into a string.

str(Birth_year)

But there are numerous ways to avoid the explicit call to str (and they are all more efficient than piecing together a single string using ):

"Your DOB is...%s!" % (Birth_Year,)  # Oldest, least recommended
"Your DOB is...{}!".format(Birth_Year)  # Better, occasionally best
f"Your DOB is...{Birth_Year}!"  # Usually best

CodePudding user response:

Here the command you are using to convert a string to a number is correct and you can indeed use int(string) assuming the string is of a valid number, like say "3". But here as your error message suggests you are trying to pass it an invalid value of "December" which cannot be converted to an int directly. So perhaps you can use the number of the month instead?

  • Related