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"?
As @Jon commented,
casefold()is better thanlower()We can use
casefold()One way is to lowercase your dictionary key.
then ask user
#output