原字符串为str,原意将前端发送过来的post请求体中的数据单独匹配出来。
1,使用正则表达式根据&符号切割成数据单独的列表
格式如: [user_name = gf,sex = 1,hobby = 1,hobby = 2,hobby = 3,file ='',about = fdg,jiguan = 1]
2,使用for循环格式,将列表中的内容遍历出来,并添加到字典中【注意,需要提前在外部建立一个空字典】
3,使用in方法,判断字典中是否存在这个对应的键,如果存在,则就是相同的键 需要把值进行拼接重新赋值给这个键;如果不存在,则直接把遍历的列表中的键和值 添加到字典中。以下代码可以直接拷贝运行。
import re
str='''user_name=gf&pwd=&sex=1&hobby=1&hobby=2&hobby=3&file=&about=fdg&jiguan=1'''
print(str)
data_finaall = re.findall('(.*?=.*?)&', str)
split_data = re.split('&', str)
print(split_data)
print(data_finaall)
data_dict=dict()
for key in split_data:
# user_name = gf
# pwd =
# sex = 1
# hobby = 1
# hobby = 2
# hobby = 3
# file =
# about = fdg
# jiguan = 1
split_data_key = re.split('=', key)
#================================================================
# print(split_data_key)
# ['user_name', 'gf']
# ['pwd', '']
# ['sex', '1']
# ['hobby', '1']
# ['hobby', '2']
# ['hobby', '3']
# ['file', '']
# ['about', 'fdg']
# ['jiguan', '1']
#================================================================
if split_data_key[0] in data_dict:
data_dict[split_data_key[0]]=split_data_key[1]+','+data_dict[split_data_key[0]]
else:
data_dict[split_data_key[0]]=split_data_key[1]
print(data_dict)
原结果hobby属性会重复只取一个,经过此处理之后结果符合预期!
输出结果:
函数输出的内容!!! {'user_name': 'gf', 'sex': '1', 'hobby': '3,2,1', 'pwd': '', 'jiguan': '1', 'about': 'fdg', 'file': ''}