Python - How to make user input not case sensitive?

吃可爱长大的小学妹 提交于 2020-05-29 10:14:48

问题


I'm new to Python and could really use some help on this. I want to create a function to filter which files I want to open and which months and day specifically. That way, the users need to input which city(files) they want to analyze on which particular month or day. However, I want the user to be able to input something that is not case sensitive. For example, the user can input 'chicago'/'CHICAGO"/"ChIcAgO" and the it still give you the right output and not the error handling message. Here is the code I use:

def get_filters ():

    city_options = ['Chicago','New York City','Washington']
    month_options = ['January','February','March','April','May','June','All']
    day_options = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday','All']
    while True:
        try:
            city = city_options.index(input('\nInsert name of the city to analyze! (Chicago, New York City, Washington)\n'))
            month = month_options.index(input('\nInsert month to filter by or "All" to apply no month filter! (January, February, etc.)\n'))
            day = day_options.index(input('\nInsert day of the week to filter by or "All" to apply no day filter! (Monday, Tuesday, etc.)\n'))
            return city_options[city].lower(), month_options[month].lower(), day_options[day].lower()
        except ValueError:
            print ("Your previous choice is not available. Please try again")

def load_data (city,month,day):

    #load data file into DataFrame
    df = pd.read_csv(CITY_DATA[city].lower())

    #convert start time column (string) to datetime
    df['Start Time']=pd.to_datetime(df['Start Time'])

    #create new column to extract month and day of the week from start time
    df['Month'] = df['Start Time'].dt.month
    df['Day_of_Week'] = df['Start Time'].dt.weekday_name

    #filter by month if applicable
    if month.lower()!= 'All':
        #use the index of the month list to get corresponding into
        months = ['January', 'February', 'March', 'April', 'May', 'June']
        month = months.index(month) + 1
        #filter by month to create new dataframes
        df = df[df['Month'] == month]

    if day.lower()!= 'All':
        #filter by day_of_week to create new DataFrames
        df =df[df['Day_of_Week'] == day]

    return(df)

回答1:


The best way to do so is just take the required input and convert it into the required case.

Use the inbuilt functions of python

variable.lower()

or

variable.upper()



回答2:


You should use str.casefold to remove case sensitivity. As per the docs, this is stricter than str.lower:

str.casefold()

Return a casefolded copy of the string. Casefolded strings may be used for caseless matching.

Casefolding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string. For example, the German lowercase letter 'ß' is equivalent to "ss". Since it is already lowercase, lower() would do nothing to 'ß'; casefold() converts it to "ss".

For example:

x = 'ßHello'

print(x.casefold())

sshello



回答3:


I am new too but I think you should look at string functions. Presuming you use python 3 since you use input and get no ValueError, you can just add .lover().title() after the parentheses of the input

Example:

city = city_options.index(input('\nInsert name of the city to analyze! (Chicago, New York City, Washington)\n').lower().title())

Should do the trick as like If you input cHIcaGO it will be converted to Chicago instantly.

Hope it helps!

Edit:(After correcting misspelling of lower() function tried it on webbrowser, pycharm and Python itself. Works just fine for me(I'm using python 2.7 so I corrected all inputs as raw_input,If you are using python 3 you don't have to change them. ).)



来源:https://stackoverflow.com/questions/50192965/python-how-to-make-user-input-not-case-sensitive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!