[英]python, re.sub add a white space every 'x' characters
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 "): 只需匹配三个字母“((\\ w \\ w \\ w)”,然后将其替换为自己加上一个空格(“ \\ 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 (?!$)": 要消除尾随空格,可以将否定表示为“ Not not 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. 如果要将组大小作为参数,可以在\\ w后面将字母计数指定为量词({n})来定义大小。 Eg: 例如:
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: 使用re findall
并以这种方式join
:
s='ABCDEFGHIJLM'
n=3
pattern= '.'*n
' '.join(re.findall(pattern, s))
'ABC DEF GHI JLM'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.