Search code examples
pythonarraysstringstrip

Python strip() function - remove characters before/after string


I am trying to remove everything in the following array except for the two numbers and the , in between.

This is the array: [array([[ 1948.97753906, 1058.23937988]], dtype=float32)]

This array is always changing in size (can have 1 pair of numbers or 6 pairs etc) and being filled with different numbers, however, the format always remains the same.

I currently have the below code, however, I think this is only working when there is one pair of numbers in the array??

final = str(self.lostfeatures).strip('[array([[ ').strip(']], dtype=float32)')

Any help would be greatly appreciated!


Solution

  • if that is really just a prefix/suffix, use replace:

    final = str(self.lostfeatures).replace('[array([[','').replace(']], dtype=float32)', '')
    

    You can do something similar with regex:

    numbers = re.findall('(?P<number>\d+\.\d+)', str(self.lostfeatures))
    

    which will also give you an array of the numbers themselves (so it's trivial to cast to float from there).

    However... if you are doing str(lostfeatures), the original must already be in an array. Why are you even casting to string? You should be able to extract the numerical array directly like this:

    lostfeatures[0][0]
    

    (you appear to have two levels of indirection... lostfeatures[0] = array([[ 1948.97753906, 1058.23937988]], then lostfeatures[0][0] == [1948.97753906, 1058.23937988]). It's not clear exactly what your data structure looks like, but that would be by far the fastest.