1

I have this string:

"[22.190894440000001, -100.99684750999999] 6 2011-08-28 19:48:11 @Karymitaville you can dance you can give having the time of my life(8) ABBA :D"

Where

  1. the two numbers inside the [] are lat and lang
  2. 6 is value
  3. 2011-08-28 is the date
  4. 19:48:11 is the time
  5. rest is the text

I want to separate this string into a list of length 5, in the following format: [lat, lang, value, date, time, text]

what is the most efficient way to do so?

3
  • 1
    You could use regex to parse the string. docs.python.org/3/library/re.html Commented Nov 11, 2020 at 9:23
  • 1
    Can you share what you’ve tried / researched on the subject yourself, before posting to SO? Please update the question accordingly. Commented Nov 11, 2020 at 9:25
  • Show what you have tried Commented Nov 11, 2020 at 9:25

2 Answers 2

2

You can make use of str.split with maxsplit argument controlling the number of splits. Then you can strip the comma and brackets from lat and lang:

>>> text = "[22.190894440000001, -100.99684750999999] 6 2011-08-28 19:48:11 @Karymitaville you can dance you can give having the time of my life(8) ABBA :D"
>>> lat, lang, value, date, time, text = text.split(maxsplit=5)
>>> lat, lang, value, date, time, text
('[22.190894440000001,', '-100.99684750999999]', '6', '2011-08-28', '19:48:11', '@Karymitaville you can dance you can give having the time of my life(8) ABBA :D')
>>> lat = lat.strip('[').rstrip(',')
>>> lang = lang.rstrip(']')
>>> lat, lang, value, date, time, text
('22.190894440000001', '-100.99684750999999', '6', '2011-08-28', '19:48:11', '@Karymitaville you can dance you can give having the time of my life(8) ABBA :D')
Sign up to request clarification or add additional context in comments.

Comments

1

Here is a solution using regex.

import re

text = "[22.190894440000001, -100.99684750999999] 6 2011-08-28 19:48:11 @Karymitaville you can dance you can give having the time of my life(8) ABBA :D"
regex = re.compile(r"\[(?P<lat>\d+.\d+), +(?P<lang>-?\d+.\d+)\] +(?P<value>.+?) *(?P<date>.+?) +(?P<time>.+?) +(?P<text>.*)")

result = regex.match(text)

print(result.group("lat"))
print(result.group("lang"))
print(result.group("value"))
print(result.group("date"))
print(result.group("time"))
print(result.group("text"))

The result:

22.190894440000001
-100.99684750999999
6
2011-08-28
19:48:11
@Karymitaville you can dance you can give having the time of my life(8) ABBA :D

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.