Skip to content

[python] string compare disregarding white space

dsindex edited this page Jul 29, 2014 · 6 revisions

reference 1
reference 2

흥미로운 내용이다. python에서 두 문자열을 비교할때, whitespace를 무시하고 비교하는 방법

using string.translate

import string
NULL = string.maketrans("","")
WHITE = string.whitespace
WHITE_MAP = dict.fromkeys(ord(c) for c in WHITE)

def compare(a,b):
     """
     Compare two base strings, disregarding whitespace
     """
     # unicode의 경우
     if isinstance(a, unicode):
         astrip = a.translate(WHITE_MAP)
     # unicode가 아닌 경우
     else:
         astrip = a.translate(NULL, WHITE)
     if isinstance(b, unicode):
         bstrip = b.translate(WHITE_MAP)
     else:
         bstrip = b.translate(NULL, WHITE)
     return astrip == bstrip

using re

import re
def compare(a, b):
    """
    Compare two base strings, disregarding whitespace
    """
    return re.sub("\s*", "", a) == re.sub("\s*", "", b)
  • 참고로 여러개의 공백을 하나로 normalize한 다음 비교하는 방법은 아래와 같다.
def compare(a, b):
    """
    Compare two base strings, normalizing whitespace
    """
    return re.sub("\s*", " ", a) == re.sub("\s*", " ", b)

using replace

def compare(a, b):
    return a.replace(" ","") == b.replace(" ","")

string.translate, re.sub, string.replace 처리 속도 테스트

  • 단순 비교를 위해서, utf8 string, whitespace는 공백만 있다고 가정하자.
#!/usr/bin/env python
#-*- coding: utf8 -*-

import os
import sys
import re
from   optparse import OptionParser
import time
import string
import timeit

# --verbose
VERBOSE = 0

NULL  = string.maketrans("","")
WHITE = string.whitespace
WHITE_MAP = dict.fromkeys(ord(c) for c in WHITE)

a = "ab cd ef"
b = "a b c d e f"

def compare_translate(a,b):
    """
    Compare two base strings, disregarding whitespace
    """
    # unicode의 경우
    if isinstance(a, unicode):
        astrip = a.translate(WHITE_MAP)
    # unicode가 아닌 경우
    else:
        astrip = a.translate(NULL, WHITE)
    if isinstance(b, unicode):
        bstrip = b.translate(WHITE_MAP)
    else:
        bstrip = b.translate(NULL, WHITE)
    return astrip == bstrip

def compare_translate_utf8(a,b):
    """
    Compare two base strings, disregarding whitespace
    """
    return a.translate(NULL, WHITE) == b.translate(NULL, WHITE)

def compare_re(a, b):
    """
    Compare two base strings, disregarding whitespace
    """
    return re.sub("\s*", "", a) == re.sub("\s*", "", b)

def compare_replace(a, b):
    return a.replace(" ","") == b.replace(" ","")

if __name__ == '__main__':

    parser = OptionParser()
    parser.add_option("--verbose", action="store_const", const=1, dest="verbose", help="verbose mode")
    (options, args) = parser.parse_args()

    if options.verbose == 1 : VERBOSE = 1

    startTime = time.time()

    t = timeit.Timer(stmt="test.compare_translate_utf8(test.a,test.b)", setup="import test")
    print "translate : " + str(t.timeit(100000))
    t = timeit.Timer(stmt="test.compare_re(test.a,test.b)", setup="import test")
    print "re : " + str(t.timeit(100000))
    t = timeit.Timer(stmt="test.compare_replace(test.a,test.b)", setup="import test")
    print "replace : " + str(t.timeit(100000))
  • 실행 결과는 아래와 같다.

translate : 0.171314001083
re : 1.36332392693
replace : 0.144765138626

  • 결과적으로 simple is best
Clone this wiki locally