pythonintegervalueconverter

How can i convert this string to integers & other strings in Python


I got this string...

String = '-268 14 7 19  - Fri Aug  3 12:32:08 2018\n'

I want to get the first 4 numbers (-268, 14, 7, 19) in integer-variables and Fri Aug 3 12:32:08 in another string-variable.

Is that possible?


Solution

  • Using basic python

    string = '-268 14 7 19  - Fri Aug  3 12:32:08 2018\n'
    vals, date = string.strip().split(' - ')
    int_vals = [int(v) for v in vals.split()]
    
    print(int_vals)  # [-268, 14, 7, 19]
    print(date)  # Fri Aug 3 12:32:08 2018
    

    Using regex

    import re
    match = re.search(r'([-\d]+) ([-\d]+) ([-\d]+) ([-\d]+)[ -]*(.*)', string)
    
    date = match.group(5)
    int_vals = [int(v) for v in match.groups()[:4]]  # same results