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?
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?
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'
Use re findall
and join
this way:
s='ABCDEFGHIJLM'
n=3
pattern= '.'*n
' '.join(re.findall(pattern, s))
'ABC DEF GHI JLM'