Search code examples
pythonstringsubstring

Python: Extract and save string between special characters using a foor loop


I have a longer string which contains numbers seperated by # (see example below). I would like to use a for loop to store the number sequences between characters in individual arrays.

#
1 2 3 4 3 8
#
6 9 2 5 7 8
#
2 0 1 6 7 2
#

How could I proceed? Thanks in advance!


Solution

  • What about plain old loop?

    for line in long_string.split("\n"):
        if line != '#':
            numbers = list(map(int, line.split(" ")))
            print(numbers)
    

    Which outputs:

    [1, 2, 3, 4, 3, 8]
    [6, 9, 2, 5, 7, 8]
    [2, 0, 1, 6, 7, 2]
    

    You could also go with

    for line in long_string.split("\n"):
        try:
            numbers = list(map(int, line.split(" ")))
            print(numbers)
        except ValueError:
            pass
    

    But be careful as this will completely ignore the lines where there are alphanumeric characters.