我希望拆分号码与另一个角色.
例
输入:
we spend 100year
Run Code Online (Sandbox Code Playgroud)
输出:
we speed 100 year
Run Code Online (Sandbox Code Playgroud)
输入:
today i'm200 pound
Run Code Online (Sandbox Code Playgroud)
产量
today i'm 200 pound
Run Code Online (Sandbox Code Playgroud)
输入:
he maybe have212cm
Run Code Online (Sandbox Code Playgroud)
输出:
he maybe have 212 cm
Run Code Online (Sandbox Code Playgroud)
我试过re.sub(r'(?<=\S)\d', ' \d', string)和re.sub(r'\d(?=\S)', '\d ', string),这是行不通的.
这样做:
ins='''\
we spend 100year
today i'm200 pound
he maybe have212cm'''
for line in ins.splitlines():
line=re.sub(r'\s*(\d+)\s*',r' \1 ', line)
print line
Run Code Online (Sandbox Code Playgroud)
打印:
we spend 100 year
today i'm 200 pound
he maybe have 212 cm
Run Code Online (Sandbox Code Playgroud)
同一行文本中多个匹配的语法相同:
>>> re.sub(r'\s*(\d+)\s*',r' \1 ', "we spend 100year + today i'm200 pound")
"we spend 100 year + today i'm 200 pound"
Run Code Online (Sandbox Code Playgroud)
捕获组(通常)从左到右编号,并且\number指的是匹配中的每个编号组:
>>> re.sub(r'(\d)(\d)(\d)',r'\2\3\1','567')
'675'
Run Code Online (Sandbox Code Playgroud)
如果它更容易阅读,您可以命名您的捕获组而不是使用\1 \2表示法:
>>> line="we spend 100year today i'm200 pound"
>>> re.sub(r'\s*(?P<nums>\d+)\s*',r' \g<nums> ',line)
"we spend 100 year today i'm 200 pound"
Run Code Online (Sandbox Code Playgroud)