Split string based on whitespace and add it to a list

Question:

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

my_text = ‘101n102n103nn111n112n113n’

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

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

I’ve tried:

def my_list(*args, end='nn'):
    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.

Asked By: Shane Heupel

||

Answers:

Just append to the final entry in the list, when you get an empty line, add a new empty list. I assume here that you’re passing in the whole string. Your *args thing doesn’t make much sense, but you didn’t show us how it would be called.

def my_list(text):
    result = [[]]
    for arg in text.split('n'):
        if not arg:
            result.append([])
        else:
            result[-1].append(int(arg))
    result.pop()
    return result
Answered By: Tim Roberts

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

my_text_parts = my_text.split('nn')

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)
Answered By: Andrew

You can do it like this:

def create_lists(my_text):
    # Split the string into a list of substrings by two 'n' characters
    substrings = my_text.rstrip().split('nn')

    # Create a list of lists by splitting each substring by 'n' characters
    lists = [substring.split('n') for substring in substrings]

    # Convert the list of lists to a list of lists of integers
    lists = [[int(x) for x in lst] for lst in lists]

    # Return the list of lists
    return lists

In this function, we first split the input string into a list of substrings by two n characters using the split() method. Then, we create a list of lists by splitting each substring by n characters using a list comprehension.

Next, we convert the list of lists to a list of lists of integers by using a nested list comprehension that converts each string element in the list to an integer using the int() function. Finally, we return the list of lists of integers.

You can test the function using the following code:

my_text = '101n102n103nn111n112n113n'

lists = create_lists(my_text)

print(lists)

[[101, 102, 103], [111, 112, 113]]
Answered By: Joan Lara Ganau
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.