Delete the substring

I examined how to delete the substring obtained by using re in python from the original string, so instead of a memo.

The following two things came to my mind

  1. Cut the original character string based on the position information of the sub character string and join them together.
  2. Replace the substring.

If you feel that you have tested several patterns using timeit, 1 seems to be faster, so I adopted this.

The code used for the test is as follows.

import timeit
import re


test_str = '...Something string...'
pat = re.compile('...Something regular expression...')
match = pat.search(test_str)


def _remove_str1(base_str, target):
    """ match_base based on object data_Disconnect str and reconnect"""
    start = target.start()
    end = target.end()
    return base_str[:start] + base_str[end:]


def _remove_str2(base_str, target):
    """ match_Based on object data
    base_Replace the relevant part of str with an empty string"""
    return base_str.replace(target.group(), '') 


def run1():
    _remove_str1(test_str, match)


def run2():
    _remove_str2(test_str, match)


if __name__ == '__main__':
    t = timeit.Timer('run1()',
            'from %s import run1' % __name__)
    print t.timeit()

    t2 = timeit.Timer('run2()',
            'from %s import run2' % __name__)
    print t2.timeit()

Recommended Posts

Delete the substring
Can you delete the file?
Delete tweets for the specified period
Delete all pyc files under the specified directory
In bash, "Delete the file if it exists".