[英]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在哪里
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.split
和maxsplit
参数来控制分割数。 Then you can strip
the comma and brackets from lat
and lang
:然后你可以从
lat
和lang
中strip
逗号和括号:
>>> 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.