Returning the month index/number instead of month name

Question:

self.months = ('January', 'February', 'March',
                        'April', 'May', 'June', 'July', 'August',
                        'September', 'October', 'November', 'December')

self.option_var = tk.StringVar(self)

        # option menu
        option_menum = ttk.OptionMenu(
            self,
            self.option_var,
            self.months[0],
            *self.months,
            )

birth_month = self.option_var.get()

so, I’m programming an age calculator in python + tkinter and I’m wondering if instead of returning the month name ("Jan"…), I can return a number, or rather the month’s index in the list.

Asked By: Red

||

Answers:

How about making self.months a list?

self.months = ['January', 'February', 'March',
                        'April', 'May', 'June', 'July', 'August',
                        'September', 'October', 'November', 'December'] 

and then use .index(), e.g.

month_you_are_looking_for = "March"

month_as_integer = self.months.index(month_you_are_looking_for)+1

As @h4z3 pointed out in the comments, the same works if you want to use your months in a tuple, as you originally did!

Answered By: Crazy Engineer
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.