Yasath Dias Yasath Dias - 1 month ago 4x
Python Question

How to shorten year into two-number integer in Python?

I have a basic block of code, and a portion of it asks the user their year of birth. In order to complete the program, I need their year (e.g. 1997) to be shortened into a two-number integer (e.g. 97). At the moment, the only way I can work out is to subtract 2000, but obviously that barely works.

year=input("And finally, what's the year of your birthday? ")

I have researched online into slicing strings and integers but none of them seem to work for me. I'm still extremely basic at Python but I'm guessing that there should be a way to select only the last two characters in an integer?:


That doesn't seem to work for me, though. Hopefully, someone will have an answer that works!

Thank you very much!


You don't validate the input so using slicing or modulo could give you nonsensical output, you should use a while loop and verify the user enters a year in some realistic range which if you go by the verified oldest person in the world is 1875-now:

import datetime

this_year = str(datetime.datetime.now().year)
while True:
    year = input("And finally, what's the year of your birthday? ")
    if "1875" <= year <= this_year:
        short_year = year[-2:]
    print("{} is not a valid year\n"
          "Please enter a year between 1875 and {}".format(year, this_year))