1

Given I want to insert a space after every third character in a string, except for after the last one.

This is how far I got:

re.sub('(.{3})','\\1 ',i)

But I didn't find an elegant way to skip the last insert, for cases where len(i)%3=0.

Any idea?

re.sub('(.{3})$-','\\1 ',i)

does not help at all.

Thanks

szeta
  • 589
  • 1
  • 5
  • 21

1 Answers1

3

Use negative lookahead to check that a match is not at the end of the string:

In [2]: s = "abcdefghi"

In [3]: re.sub(r'(.{3})(?!$)','\\1 ', s)
Out[3]: 'abc def ghi'

You can also proceed with a non-regex option by slicing the string and joining the sliced parts:

In [4]: " ".join(s[i: i + 3] for i in range(0, len(s), 3))
Out[4]: 'abc def ghi'
Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195