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

45 views Asked by At

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?

3

There are 3 answers

3
FHTMitchell On BEST ANSWER

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
1
Rakesh On

Use str.split

Ex:

String = '-268 14 7 19  - Fri Aug  3 12:32:08 2018\n'
first, second = String.split(" - ")
first = tuple(int(i) for i in first.split())
print(first)
print(second)

Output:

(-268, 14, 7, 19)
Fri Aug  3 12:32:08 2018
0
Lev Zakharov On

Use split and map for it:

left, date = String.split(' - ')
numbers = list(map(int, left.split()))

print(numbers, date)