1
string = 'ABCDEFGHIJLM'

I'm trying to achieve the following result using

re.sub(SOME CODE HERE):
'ABC DEF GHI JLM'

Is it possible to do that?

xkdo
  • 33
  • 1
  • 6
  • To format the table/code/error correctly, please add **4 leading** space to each line of the table. Thanks! –  Nov 12 '17 at 03:03
  • Possible duplicate of [Regex insert space every third character, except at end of line](https://stackoverflow.com/questions/32981050/regex-insert-space-every-third-character-except-at-end-of-line) – Van Peer Nov 12 '17 at 03:11

2 Answers2

2

Just match three letters "(\w\w\w)" and replace them with themselves plus a space ("\1 "):

print re.sub(r'(\w\w\w)', r'\1 ', 'ABCDEFGHIJLM')

Prints:

'ABC DEF GHI JLM '

To get rid of the trailing space, you can put a negative look-ahead of "Not end of string (?!$)":

print re.sub(r'(\w\w\w)(?!$)', r'\1 ', 'ABCDEFGHIJLM')

Prints:

'ABC DEF GHI JLM'

If you want to make the group size a parameter, you can specify the letter count as a quantifier ({n}) after the \w to define the size. E.g.:

group_size = 2
print re.sub(r'(\w{%d})(?!$)' % group_size, r'\1 ', 'ABCDEFGHIJLM')

Prints:

'AB CD EF GH IJ LM'
Sven Zwei
  • 631
  • 7
  • 5
0

Use re findall and join this way:

 s='ABCDEFGHIJLM'
 n=3
 pattern= '.'*n 
 ' '.join(re.findall(pattern, s))
'ABC DEF GHI JLM'
skrubber
  • 1,095
  • 1
  • 9
  • 18