Trying to do the following: string = "2" replace to = "No 2"
using below regex in python:
re.sub(r'(.*)', r'No. \g<1>', '2')
But it returns:
'No. 2No. '
Can you please help what's going wrong?
Note: using 3.8.5 python version
For me it works (maybe different python versions... I'm using 3.6.11 and it seems like 3.8's [which I assume OP is using] re
works differently):
In [1]: import re
In [2]: re.sub(r'(.*)', r'No. \g<1>', '2')
Out[2]: 'No. 2'
But, I would suggest using a better regex:
In [3]: re.sub(r'(\d+)', r'No. \g<1>', '2')
Out[3]: 'No. 2'
This is better since it only catches the digits in the string:
In [4]: re.sub(r'(\d+)', r'No. \g<1>', '2 3 4 5 blabla')
Out[4]: 'No. 2 No. 3 No. 4 No. 5 blabla'
where your regex will just take the entire string:
In [5]: re.sub(r'(.*)', r'No. \g<1>', '2 3 4 5 blabla')
Out[5]: 'No. 2 3 4 5 blabla'