Use Regex to replace uppercase abbreviations with same letters but adding punctuation and space

Viewed 131

Suppose I have a sentence such as

   string = 'USA and EU are not hosting the SWCP'

Desired output - add a . and a space after each letter

'U. S. A. and E. U. are not hosting the S. W. C. P.'

I was thinking of using re.sub() but couldn't really figure out how to express the replacement and use the letters previously found by the regex.

reg = r'[A-Z]{2,4}'
string = re.sub(reg, ???, string)
2 Answers

You can replace matches of the following regular expression with ". ".

r'(?<=[A-Z])(?=[A-Z])|(?<=[A-Z]{2}) ?'

Start your engine! <¯\(ツ)/¯> Python code

(?<=[A-Z])     : use a positive lookbehind to assert previous character
                 is a capital letter
(?=[A-Z])      : use a positive lookahead to assert next character
                 is a capital letter
|              : or
(?<=[A-Z]{2})  : use a positive lookbehind to assert 2 previous
                 characters are capital letters
[ ]?           : optionally match a space

I've represented a space in the last line above as a character class containing a space for clarity. The character class is not needed.

Note that both components of the alternation match a location that is between consecutive characters.

The optional space ? is added after (?<=[A-Z]{2}) so that if a match is made after 'C' in 'ABC hi' the regex will match the space, thereby avoiding the introduction of an extra space when the replacement is made.

Using str.isupper() and str.isalpha():

s = 'USA and EU are not hosting the SWCP'
x = ''

for char in s:
    if char.isupper() and char.isalpha():
        x += char + '.'
    else:
        x += char
        
print(x)

one-liner:

print("".join(x + "." if x.isalpha() and x.isupper() else x for x in s))

OUTPUT:

U.S.A. and E.U. are not hosting the S.W.C.P.
Related