-2

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?

Rakesh
  • 81,458
  • 17
  • 76
  • 113
Quotenbanane
  • 263
  • 1
  • 6
  • 16

3 Answers3

1

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
FHTMitchell
  • 11,793
  • 2
  • 35
  • 47
  • Ok thanks for the answer. If i understand this correctly, "split" splits the string into the integers and the timestamp and get rid of the ' - '. Then int_*val* converts the string-values into integer-values and that's it. Looks perfect. If i'd print int_vals(1) do i get -268? – Quotenbanane Aug 03 '18 at 10:54
  • Yes that's how it works. No you won't get that because this isn't matlab. `print(int_vals[0])` will get you `-268` – FHTMitchell Aug 03 '18 at 10:56
  • It's funny you found out that I'm mainly using Matlab :P I'll go with print(int_vals[0]). Thanks a lot! – Quotenbanane Aug 03 '18 at 10:59
0

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
Rakesh
  • 81,458
  • 17
  • 76
  • 113
  • Exactly what i needed! I didn't know if you or Mitchell were earlier to post the solution so i gave Mitchell the hook because he had less points :-) – Quotenbanane Aug 03 '18 at 10:58
0

Use split and map for it:

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

print(numbers, date)
Lev Zakharov
  • 2,409
  • 1
  • 10
  • 24