Home > Back-end >  Python: How to slice string next to input data
Python: How to slice string next to input data

Time:02-04

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"

CodePudding user response:

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 = {day: number for day, number in [line.split(';') for line in data.strip().split('\n')]}

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

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

CodePudding user response:

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".

CodePudding user response:

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]}"')
  •  Tags:  
  • Related