Python - 如何使用户输入不区分大小写?

LOR*_*121 3 python user-input case-insensitive

我是 Python 的新手,真的可以在这方面使用一些帮助。我想创建一个函数来过滤我想要打开的文件以及具体的月份和日期。这样,用户需要输入他们想要在哪个特定月份或日期分析哪个城市(文件)。但是,我希望用户能够输入不区分大小写的内容。例如,用户可以输入 'chicago'/'CHICAGO"/"ChIcAgO" 并且它仍然为您提供正确的输出而不是错误处理消息。这是我使用的代码:

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)
Run Code Online (Sandbox Code Playgroud)

jpp*_*jpp 6

您应该使用str.casefold来消除区分大小写。根据文档,这比str.lower

\n\n
\n

str.casefold()

\n\n

返回字符串的折叠副本。大小写折叠的字符串可用于\n 不区分大小写的匹配。

\n\n

大小写折叠类似于小写,但更激进,因为它旨在删除字符串中的所有大小写区别。例如,德语小写字母 \'\xc3\x9f\' 相当于“ss”。由于它已经是小写,lower() 不会对 \'\xc3\x9f\' 执行任何操作;casefold()\n 将其转换为“ss”。

\n
\n\n

例如:

\n\n
x = \'\xc3\x9fHello\'\n\nprint(x.casefold())\n\nsshello\n
Run Code Online (Sandbox Code Playgroud)\n


Par*_*ala 5

最好的方法是获取所需的输入并将其转换为所需的案例。

使用python的内置函数

variable.lower()
Run Code Online (Sandbox Code Playgroud)

或者

variable.upper()
Run Code Online (Sandbox Code Playgroud)