Regex insert space every third character, except at end of line

时间:2022-08-09 20:13:52

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.

但是对于len(i)%3 = 0的情况,我没有找到跳过最后一个插入的优雅方法。

Any idea?

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

does not help at all.

没有任何帮助。

Thanks

1 个解决方案

#1


2  

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'

#1


2  

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'