LoginSignup
3
5

More than 5 years have passed since last update.

部分文字列を削除する

Last updated at Posted at 2013-10-05

pythonでreを使って取得した部分文字列を元の文字列から削除する方法を検討したのでメモ代わりに。

ぱっと思いついたのは以下2つ
1.部分文字列の位置情報をもとに元の文字列を切ってつなぎ合わせる。
2.部分文字列をリプレイスする。

timeitを使って数パターンテストした感じだと1のほうが早そうなのでこちらを採用。

テストに使用したコードは以下の通り。

import timeit
import re


test_str = '...なんか文字列...'
pat = re.compile('...なんか正規表現...')
match = pat.search(test_str)


def _remove_str1(base_str, target):
    """ match_objectのデータを元にbase_strを切断してつなぎ直す """
    start = target.start()
    end = target.end()
    return base_str[:start] + base_str[end:]


def _remove_str2(base_str, target):
    """ match_objectのデータを元に
    base_strの該当個所を空文字列にリプレイス """
    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()
3
5
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5