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.
[101, 102, 103] [111, 112, 113]
I've tried:
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.
CodePudding user response:
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
CodePudding user response:
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)
CodePudding user response:
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('\n\n')
# 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 = '101\n102\n103\n\n111\n112\n113\n'
lists = create_lists(my_text)
print(lists)
[[101, 102, 103], [111, 112, 113]]