简体   繁体   English

Python 将字符串拆分成多个部分

[英]Python split string into multiple parts

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 [] 中的两个数字是 lat 和 lang
  2. 6 is value 6是价值
  3. 2011-08-28 is the date 2011-08-28 是日期
  4. 19:48:11 is the time 19:48:11 是时间
  5. rest is the text rest为正文

I want to separate this string into a list of length 5, in the following format: [lat, lang, value, date, time, text]我想将这个字符串分成一个长度为 5 的列表,格式如下: [lat, lang, value, date, time, text]

what is the most efficient way to do so?最有效的方法是什么?

You can make use of str.split with maxsplit argument controlling the number of splits.您可以使用str.splitmaxsplit参数来控制分割数。 Then you can strip the comma and brackets from lat and lang :然后你可以从latlangstrip逗号和括号:

>>> 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')

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM