4

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.

muffint0p
  • 63
  • 6

4 Answers4

4

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
Rakesh
  • 81,458
  • 17
  • 76
  • 113
3

Try this:

if 'STREET' not in address and address.find('ST.'):
    address = address.replace(' ST.',' STREET')
Hayat
  • 1,539
  • 4
  • 18
  • 32
3

Try this, the less the code the better.

address = "WEST ST."

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

print(address)
exe
  • 354
  • 3
  • 23
2

I edited your code like this:

address = "WEST ST."

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

print (address)

Here is the result:

WEST STREET

You have to replace "ST." not "ST"

cracker
  • 111
  • 4