Python将字符串拆分为多个部分
我有这个字符串:Python将字符串拆分为多个部分,python,arrays,string,list,split,Python,Arrays,String,List,Split,我有这个字符串: "[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 6是价值 2011-08-28是日期 19:48:11是时候了 剩下的就是文本 我想把这个字符串分成一个长度为5的列表,格式
"[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
6是价值
2011-08-28是日期
19:48:11是时候了
剩下的就是文本
我想把这个字符串分成一个长度为5的列表,格式如下:[lat,lang,value,date,time,text]
最有效的方法是什么?您可以使用str.split和maxsplit参数来控制拆分的数量。然后可以从lat和lang中去掉逗号和括号:
可以使用str.split和maxslit参数来控制拆分的数量。然后可以从lat和lang中去掉逗号和括号:
下面是一个使用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"))
下面是一个使用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"))
您可以使用正则表达式来解析字符串。在发布到SO之前,您能否自己分享您在该主题上的尝试/研究成果?请相应地更新问题。显示您已尝试的内容。您可以使用正则表达式解析字符串。在发布到SO之前,您能否自己分享您在该主题上的尝试/研究成果?请相应地更新问题。显示您已尝试的内容
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