这是我的输入
string = '07/08/2018 07/08/2018 IMPS DR-1763308000000116-PYTM0123456-917 592674 5,000.00 39,325.93'
我需要这样的输出
{'date1':'07/08/2018','date2':'07/08/2018','remark':'IMPS DR-1763308000000116-PYTM0123456-917 592674','credit':'5,000.00','balance' : '39,325.93' }
我试过了
result = { 'date1': list1[0], 'date2': list1[1], 'balance': list1[-1]}
print(result)
输出
{'date1': '07/08/2018', 'date2': '07/08/2018', 'balance': '39,325.93'}
您可以使用 split 来拆分字符串并使用它们,如 Scott 所述,但是如果您可以将其显示为这种格式的字符串
str = '{'date1':'07/08/2018','date2':'07/08/2018','remark':'IMPS DR-1763308000000116-PYTM0123456-917 592674','credit':'5,000.00','balance' : '39,325.93' }'
#then you can just import json and do
json = json.loads(str)
这是一个简单的解决方案——
string = '07/08/2018 07/08/2018 IMPS DR-1763308000000116-PYTM0123456-917 592674 5,000.00 39,325.93'
l = string.split()
result = {'date1': l[0],
'date2': l[1],
'remark': ' '.join((l[2],l[3])),
'credit': l[4],
'balance': l[5]}
输出
{'date1': '07/08/2018', 'date2': '07/08/2018', 'remark': 'IMPS DR-1763308000000116-PYTM0123456-917', 'credit': '592674', 'balance':'5,000.00'}
试试这个:
words = string.split(" ")
values = words[:2] + [" ".join(words[2:-2])] + words[-2:]
keys = ["date1", "date2", "remark", "credit", "balance"]
result = {}
for i in range(5):
result[keys[i]] = values[i]
print(result)
输出:
{'date1': '07/08/2018',
'date2': '07/08/2018',
'remark': 'IMPS DR-1763308000000116-PYTM0123456-917 592674',
'credit': '5,000.00',
'balance': '39,325.93'}
您可以使用扩展的可迭代解包在单个变量(列表(中获取备注的所有部分
import json
keys = ['date1', 'date2', 'remark', 'credit', 'balance']
foo = '07/08/2018 07/08/2018 IMPS DR-1763308000000116-PYTM0123456-917 592674 5,000.00 39,325.93'
date1, date2, *remarks, credit, balance = foo.split()
remarks = ' '.join(remarks)
#data as dict
data = dict(zip(keys, [date1, date2, remarks, credit, balance]))
print(data)
# if you need json string
my_json = json.dumps(data, indent=4)
print(my_json)
作为旁注 - 不要使用 string
作为变量名 - 它是 Python 标准库中的一个模块。