Delete a row and get the index of the beginning and end of the index

Is there an easy way in Python to remove a row and get the start index and end index?

Example: for a row, ' hello world! 'I want to delete the row 'hello world!', as well as the start index 2and index and index 14.

' hello world! '.strip() returns only a cut string.

I could write a function:

def strip(str):
    '''
    Take a string as input.
    Return the stripped string as well as the start index and end index.
    Example: '  hello world!   '  --> ('hello world!', 2, 14)
    The function isn't computationally efficient as it does more than one pass on the string.
    '''
    str_stripped = str.strip()
    index_start = str.find(str_stripped)
    index_end = index_start + len(str_stripped)
    return str_stripped, index_start, index_end

def main():
    str = '  hello world!   '
    str_stripped, index_start, index_end = strip(str)
    print('index_start: {0}\tindex_end: {1}'.format(index_start, index_end))

if __name__ == "__main__":
    main()

but I am wondering if Python or one popular library supports any built-in way to do this.

+4
source share
3 answers

One option (perhaps not the most direct) is to do this with regular expressions:

>>> import re
>>> s = '  hello world!   '
>>> match = re.search(r"^\s*(\S.*?)\s*$", s)
>>> match.group(1), match.start(1), match.end(1)
('hello world!', 2, 14)

where in the template ^\s*(\S.*?)\s*$:

  • ^ - beginning of line
  • \s*
  • (\S.*?) - , , , -
  • $ -
+6

- lstrip rstrip . :

s = '  hello world!   '
s2 = s.lstrip()
s3 = s2.rstrip()
ix = len(s) - len(s2)
ix2 = len(s3) + ix

:

>>> s3
'hello world!'
>>> ix
2
>>> ix2
14
>>>
+3

In fact, you have the necessary methods to complete this task. strip, findand len- all you need.

s = '  hello world!   '
s1 = s.strip()
first_index = s.find(s1)
end_index = first_index + len(s1) - 1
0
source

All Articles