Home > Software engineering >  Remove everything from array after second \n
Remove everything from array after second \n

Time:11-16

I have an array where need to remove everything after the second \n

For example numbers = ['2.05\n1.68\n2.70\n1.41\n4.70\n22.0\n5.60\n']

and need to remove everything after 1.68\n

Result need to be numbers = ['2.05\n1.68\n']

Tried with rsplit but I really don't understand how this works.

CodePudding user response:

You could use a regular expression to extract the part of the numbers string you're interested in:

import re

def extract(num_string):
    match = re.match(r'. \n. \n', num_string)
    return match.group() if match else ''

numbers = ['2.05\n1.68\n2.70\n1.41\n4.70\n22.0\n5.60\n']
result = [extract(s) for s in numbers]

gives

['2.05\n1.68\n']

This will work for any list of strings.

  • Related