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

Time:08-19

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!

CodePudding user response:

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.

CodePudding user response:

We can use re.findall here along with a list comprehension:

inp = """#
1 2 3 4 3 8
#
6 9 2 5 7 8
#
2 0 1 6 7 2
#"""

seq = [[int(x) for x in y.split()] for y in re.findall(r'\d (?:\s \d )*', inp)]
print(seq)

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