简体   繁体   中英

Python: How to slice string next to input data

I have the task to do but I don't know how can I start. In output I need to give back day name and number.

I know how to get the day name but I can't find how to get number either. Could you suggest me something.

Data for the task:

data = (
data = """
monday;1250
tuesday;1405
wednesday;1750
thursday;1100
friday;0800
saturday;1225
sunday;1355
"""

My uncompleted code:

day = input("Insert day: ").lower()

if day in data:
    print("""The day is "{}"\nThe number is: """.format(dzien))

The output should looks like:

The day is "day name"
The number is "number"

You could parse your data into a dictionary and then look up the corresponding number:

data = """
monday;1250
tuesday;1405
wednesday;1750
thursday;1100
friday;0800
saturday;1225
sunday;1355
"""

data = data.strip()
data = {day: number for day, number in [line.split(';') for line in data.split('\n')]}

day = input("Insert day: ").lower()

if day in data:
    print(f"""The day is "{day}"\nThe number is: {data[day]}""")

Convert data into dictionary:

data = {'monday' : '1250', 
        'tuesday': '1405', 
        'wednesday': '1750', 
        'thursday':'1100',
        'friday': '0800',
        'saturday':'1225',
        'sunday':'1355'}


day = input("Insert day: ").lower()

if day in data:
   print(f'The day is "{day}"\nThe number is: "{data[day]}"')

Use a dictionary. Dictionaries allow to organize data in key-value format, so you can access to the information binded to the day with data[day]. Change the code to:

data = {
    'monday': 1250,
    'tuesday': 1405,
    'wednesday': 1750,
    'thursday': 1100,
    'friday': 800,
    'saturday': 1225,
    'sunday': 1355
}

day = input("Insert day: ").lower()

if day in data:
    # get number associated with day
    day_number = data[day] 
    # print output
    print('The day is "{}".\nThe number is "{}".'.format(day, day_number))

It will print:

Insert day: monday
The day is "monday".
The number is "1250".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM