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

Split string based on whitespace and add it to a list

I need a function that takes in a string, and creates a new list every time there are two whitespace characters.

my_text = ‘101\n102\n103\n\n111\n112\n113\n’

I want to create a new list each time there’s two whitespace characters.

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

[101, 102, 103]
[111, 112, 113]

I’ve tried:

    def def my_list(*args, end='\n\n'):
        for arg in args:
            new_list = []
            if end:
                new_list.append(arg)
        print(new_list)

but that just adds all the numbers to a single list.

>Solution :

You could use the split() method to split the string on the ‘\n\n’ and ‘\n’ delimiter

my_text_parts = my_text.split('\n\n')

for text_part in my_text_parts:
    numbers = text_part.split('\n')

    new_list = []
    for number in numbers:
        new_list.append(int(number))

 print(new_list)
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