Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I have problem with when split list in Python

I have data like this :data.txt

Product list
Name                Quantity    Price           
Iphone11            5       14000000.0   
SS note 10          4       13000000.0   
Nokia C100          1       20000000.0 

and this is my code to filter the

fname = open("Data.txt")
num_line = 0
for line in fname:
    num_line += 1
    if num_line == 1 or num_line == 2:
        continue
    data = line.strip().split()
    if data == []:
        continue
    
    print(data)

And I have a result:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

['Iphone11', '5', '14000000.0']
['SS', 'note', '10', '4', '13000000.0']
['Nokia', 'C100', '1', '20000000.0']

I want my code have format like it to put into my database:

['Iphone11', '5', '14000000.0']
['SS note 10', '4', '13000000.0']
['Nokia C100', '1', '20000000.0']

please help me

>Solution :

You can use re.sub and replace all space with one space. then use str.rsplit to split from the right and set maxsplit=2 for splitting only two times and skip from the other for each line. (It’s better to use with like below, otherwise, you need to close the file after opening and reading.)

import re
with open("Data.txt") as fname:
    num_line = 0
    for line in fname:
        num_line += 1
        if num_line == 1 or num_line == 2:
            continue
            
        line = re.sub(r'(\s+)', ' ', line)
        data = line.strip().rsplit(sep=' ', maxsplit=2)
        if data == []:
            continue
        print(data)

['Iphone11', '5', '14000000.0']
['SS note 10', '4', '13000000.0']
['Nokia C100', '1', '20000000.0']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading