python中不区分大小写语句怎么写,Python-如何使用户输入不区分大小写?

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)

解决方案

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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值