Answer the question
In order to leave comments, you need to log in
How to parse text in Python?
There is a line like
ID: 001; Username: Ivan; Balance: 01.00; status: active;
str id = "001"
str username = "Ivan"
str balance = "01.00"
Answer the question
In order to leave comments, you need to log in
Here you can do without parsing with regular expressions, and use the split function of splitting the string split, which is built into each object of the string type
Further from the split result
['ID: 001', ' Username: Ivan', ' Balance: 01.00', ' Status: active ', '']
elements 0,1,2 are taken, split again by ':'
' Username: Ivan' ->[' Username',' Ivan']
and then the remaining space on the left is eliminated by taking the result string as a list of characters without null element [1:]
str1='ID: 001; Username: Ivan; Balance: 01.00; Status: active;'
out=str1.split(';')
id=out[0].split(':')[1][1:]
username=out[1].split(':')[1][1:]
balance=out[2].split(':')[1][1:]
Questions like this remind me of how "two from the box" did everything.
>>> data = "ID: 001; Username: Ivan; Balance: 01.00; Status: active;"
>>> dict(x.split(":") for x in data.replace(" ","").split(";") if ":" in x)
{'ID': '001', 'Username': 'Ivan', 'Balance': '01.00', 'Status': 'active'}
>>> import re
>>> dict(re.findall("([^:]+):\s?([^;]+);\s?",data))
{'ID': '001', 'Username': 'Ivan', 'Balance': '01.00', 'Status': 'active'}
>>>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question