I have a situation where a user submits an address and I have to replace user inputs to my keys. I can join this using an address without suffixes.
COVERED WAGON TRAIL
CHISHOLM TRAIL
LAKE TRAIL
CHESTNUT ST
LINCOLN STREET
to:
COVERED WAGON
CHISHOLM
LAKE
CHESTNUT
LINCOLN
However I can't comprehend how this code can be written to replace only the last word. I get:
LINCOLN
CHESTNUT
CHISHOLM
LAKEAIL
CHISHOLMAIL
COVERED WAGONL
I've tried regex verbose, re.sub and $.
import re
target = '''
LINCOLN STREET
CHESTNUT ST
CHISHOLM TR
LAKE TRAIL
CHISHOLM TRAIL
COVERED WAGON TRL
'''
rdict = {
' ST': '',
' STREET': '',
' TR': '',
' TRL': '',
}
robj = re.compile('|'.join(rdict.keys()))
re.sub(' TRL', '',target.rsplit(' ', 1)[0]), target
result = robj.sub(lambda m: rdict[m.group(0)], target)
print result
Use re.sub
with $
.
target = '''
LINCOLN STREET
CHESTNUT ST
CHISHOLM TR
LAKE TRAIL
CHISHOLM TRAIL
COVERED WAGON TRL
'''
import re
print re.sub('\s+(STREET|ST|TRAIL|TRL|TR)\s*$', '', target, flags=re.M)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With