T
T
timka2282020-08-20 18:23:18
Python
timka228, 2020-08-20 18:23:18

How to parse text in Python?

There is a line like

ID: 001; Username: Ivan; Balance: 01.00; status: active;

I need to get data between colons and semicolons. Those. should get 3 string with the following data:
str id = "001"
str username = "Ivan"
str balance = "01.00"

How can I get them? Please tell me the code.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
P
PavelMos, 2020-08-20
@timka228

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:]

A
Alexander, 2020-08-20
@NeiroNx

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'}
>>>

D
Drill, 2020-08-20
@Drill

text ='ID: 001; Username: Ivan; Balance: 01.00; Status: active;'

for key,val in (x.strip().split(': ') for x in text.split(';') if x):
    print(f"{key} = {val}")

ID = 001
Username = Ivan
Balance = 01.00
Status = active

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question