Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python .replace 'st' with 'street' but leave street name the same

I'm trying to change st. to street, ave. to avenue, etc. using .replace() for addresses in a single cell. For example: WEST ST. should be WEST STREET or MOUNT PEBBLE RD. should be MOUNT PEBBLE ROAD

Here is my code:

if 'STREET' not in address and address.find('ST.'):
    address = address.replace('ST','STREET')

The result gives me WESTREET STREET. How can I leave the address name untouched without altering the address name? I tried .split() but most cells had different list lengths so it got really confusing.

like image 235
muffint0p Avatar asked Dec 13 '22 13:12

muffint0p


1 Answers

Try using Regex with boundaries.

Ex:

import re

s = """WEST ST
       MOUNT PEBBLE RD"""

toReplace = {"ST": 'STREET', "RD": "ROAD", "ave": "avenue"}
for k,v in toReplace.items():
    s = re.sub(r"\b" + k + r"\b", v, s)
print(s)

Output:

WEST STREET
MOUNT PEBBLE ROAD
like image 139
Rakesh Avatar answered Dec 22 '22 15:12

Rakesh