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

2024-07-02 09:44:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个字符串:

"[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"

在哪里

  1. []中的两个数字是lat和lang
  2. 6是价值
  3. 2011-08-28是日期
  4. 19:48:11是时候了
  5. 剩下的就是文本

我想用以下格式将这个字符串分成一个长度为5的列表:[lat, lang, value, date, time, text]

最有效的方法是什么


Tags: ofthe字符串youlangtimemycan
2条回答

您可以使用str.splitmaxsplit参数来控制拆分的数量。然后您可以striplatlang中选择逗号和括号:

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

下面是一个使用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"))

结果是:

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

相关问题 更多 >