Home > Mobile >  Python slicing output
Python slicing output

Time:12-14

I have a school project on analyzing logs & roughly, I need to be able to retrieve the day & time from a line in the format "MM DD HH:MM:SS" and it always shows as "['MM DD HH:MM:SS']"

def get_complete_date(line):
    """ 
    Pre : line est une ligne de log bien formée (str)
    Post : Retourne la date et l'heure sous forme de chaine de caractère sans changer le format.
    """
    # splt = line.split(sep=" ", maxsplit=5)
    # dt = splt[2] 
    

    complete_date = line.split(" ")
    
    # print(complete_date)

    return complete_date[0:3]

CodePudding user response:

Very naive approach, but if the length of datetime part is the same (same pattern on each line), you can simply slice it from 0 to pattern length:

def get_complete_date(l):
    tpl = "MM DD HH:MM:SS"
    return l[0: len(tpl)]

line = "MM DD HH:MM:SS some text"

print(get_complete_date(line))
>>>'MM DD HH:MM:SS'

CodePudding user response:

You almost there it's issue with slicing.

def get_complete_date(line):
    """ 
    Pre : line est une ligne de log bien formée (str)
    Post : Retourne la date et l'heure sous forme de chaine de caractère sans changer le format.
    """
    # splt = line.split(sep=" ", maxsplit=5)
    # dt = splt[2] 
    

    complete_date = line.split(" ")
    
    # print(complete_date)

    return complete_date[1:3:1]

line = "MM DD HH:MM:SS"

print(get_complete_date(line))

Gives #

['DD', 'HH:MM:SS']

Explination your slicing should be

[1:3:1] = [start:stop:step]

0th elemnt is month which you don't need start from 1

  • Related