How can I make user entries case-insensitive in Python 3?

87 views Asked by At

I am following FreeCodeCamp's Python tutorial. I would like to know how I can make user entries case-insensitive.

Here is the example code.

month_conversions = {
    "Jan": "January",
    "Feb": "February",
    "Mar": "March",
    "Apr": "April",
    "May": "May",
    "Jun": "June",
    "Jul": "July",
    "Aug": "August",
    "Sep": "September",
    "Oct": "October",
    "Nov": "November",
    "Dec": "December",
}

print(month_conversions.get("Jan")

And it will always return "January".

Suppose I wanted the flexibility of the user entering "JAN", "jan" and "Jan" and the programme always returning "January". How would I do that?

I re-wrote the months into a list, then referred to their index which should produce the whole name of the month. Like this:

month_key = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]

month_conversions = {
    month_key[0]: "January",
    month_key[1]: "February",
    month_key[2]: "March",
    month_key[3]: "April",
    month_key[4]: "May",
    month_key[5]: "June",
    month_key[6]: "July",
    month_key[7]: "August",
    month_key[8]: "September",
    month_key[9]: "October",
    month_key[10]: "November",
    month_key[11]: "December",
}

print(month_conversions.get("Jan"))

And I was happy it gave me January! But using the .get command, how can I ensure that a user can type "JAN", "jan" and "Jan" and return "January"?

2

There are 2 answers

0
Talha Tayyab On

As @Jon commented, casefold() is better than lower()

We can use casefold()

One way is to lowercase your dictionary key.

month_conversions = {
    "jan": "January",
    "feb": "February",
    "mar": "March",
    "apr": "April",
    "may": "May",
    "jun": "June",
    "jul": "July",
    "aug": "August",
    "sep": "September",
    "oct": "October",
    "nov": "November",
    "dec": "December",
}

then ask user

user = input('Enter month please : ')
l_case = user.casefold()
print(month_conversions.get(l_case))

#output

Enter month please : Jan
January

Enter month please : JAN
January

Enter month please : jan
January
0
TYZ On

Similar to Goku's solution, you can use string.capitalize() in Python without changing the key of your dictionary.

user = input('Enter month please : ')
print(month_conversions.get(user.capitalize()))

The capitalize method will convert first character to uppercase and all other to lowercase.