can you write a str.replace() using dictionary values in Python?

后端 未结 10 847
小鲜肉
小鲜肉 2020-12-03 00:20

I have to replace the north, south, etc with N S in address fields.

If I have

list = {\'NORTH\':\'N\',\'SOUTH\':\'S\',\'EAST\':\'E\',\'WEST\':\'W\'}         


        
10条回答
  •  抹茶落季
    2020-12-03 01:25

    One option I don't think anyone has yet suggested is to build a regular expression containing all of the keys and then simply do one replace on the string:

    >>> import re
    >>> l = {'NORTH':'N','SOUTH':'S','EAST':'E','WEST':'W'}
    >>> pattern = '|'.join(sorted(re.escape(k) for k in l))
    >>> address = "123 north anywhere street"
    >>> re.sub(pattern, lambda m: l.get(m.group(0).upper()), address, flags=re.IGNORECASE)
    '123 N anywhere street'
    >>> 
    

    This has the advantage that the regular expression can ignore the case of the input string without modifying it.

    If you want to operate only on complete words then you can do that too with a simple modification of the pattern:

    >>> pattern = r'\b({})\b'.format('|'.join(sorted(re.escape(k) for k in l)))
    >>> address2 = "123 north anywhere southstreet"
    >>> re.sub(pattern, lambda m: l.get(m.group(0).upper()), address2, flags=re.IGNORECASE)
    '123 N anywhere southstreet'
    

提交回复
热议问题