Efficiently carry out multiple string replacements in Python

后端 未结 2 861
星月不相逢
星月不相逢 2020-12-09 12:50

If I would like to carry out multiple string replacements, what is the most efficient way to carry this out?

An example of the kind of situation I have encountered

2条回答
  •  旧时难觅i
    2020-12-09 13:40

    You may find that it is faster to create a regex and do all the replacements at once.

    Also a good idea to move the replacement code out to a function so that you can memoize if you are likely to have duplicates in the list

    >>> import re
    >>> [re.sub('[aeiou]','',s) for s in strings if len(s) > 2]
    ['a', 'lst', 'of', 'strngs']
    
    
    >>> def replacer(s, memo={}):
    ...   if s not in memo:
    ...     memo[s] = re.sub('[aeiou]','',s)
    ...   return memo[s]
    ... 
    >>> [replacer(s) for s in strings if len(s) > 2]
    ['a', 'lst', 'of', 'strngs']
    

提交回复
热议问题