0

I am working with UK post code data and, from what I've seen, they usually have 5, 6 or 7 characters with a space between them; examples include "EC2A 2FA", "HU8 9XL" and "E1 6AW". The problem I have is that some of the post codes in the dataset do not have a space for example "EC2A2FA", "HU89XL" and "E16AW"; this causes them not to be found when I try to get their location.

I want to add spaces to the ones that don't have one and leave the ones that already have a space. I could probably use if statements to check for a space at a particular index and add a space if it is not already there but I want to know if their is a more efficient method to add the spaces between them like, for example, using string formatting.

# If I have this list
post_codes = ["BH16 6FA", "HU37FD", "W4 5YE", "E50QD", "WC2H9JQ", "LE3 0PD"]

# I want to get 
["BH16 6FA", "HU3 7FD", "W4 5YE", "E5 0QD", "WC2H 9JQ", "LE3 0PD"]
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Dappa jack
  • 145
  • 1
  • 2
  • 12

1 Answers1

1

You can use negative numbers in slices to isolate characters at the end of the string. When a space is lacking, split out the last 3 characters and insert the space.

post_codes = ["fEC2A 2FA", "E1 6AW", "EC2A2FA", "HU89XL", "E16AW"]

for idx, code in enumerate(post_codes):
    if " " not in code:
        post_codes[idx] = code[:-3] + " " + code[-3:]
print(post_codes)
tdelaney
  • 73,364
  • 6
  • 83
  • 116