0

In python,

with re.sub, how I can replace a substring with a new string ?

from

number = "20"
s = "hello number 10, Agosto 19"

to

s = "hello number 20, Agosto 19"

I try

re.sub(r'number ([0-9]*)', number, s)

EDIT

the number 10 is a example, the number in the string can be any number.

JuanPablo
  • 23,792
  • 39
  • 118
  • 164

3 Answers3

6

You mean this?

>>> import re
>>> m = re.sub(r'10', r'20', "hello number 10, Agosto 19")
>>> m
'hello number 20, Agosto 19'

OR

Using lookbehind,

>>> number = "20"
>>> number
'20'
>>> m = re.sub(r'(?<=number )\d+', number, "hello number 10, Agosto 19")
>>> m
'hello number 20, Agosto 19'
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
2

Do not use regex for such simple cases. Normal string manipulation is enough (and fast):

s = "hello number 10, Agosto 19"
s = s.replace('10', '20')
hjpotter92
  • 78,589
  • 36
  • 144
  • 183
  • 2
    Unless of course `'1010'` shouldn't be converted to `'2020'` and the OP is omitting the fact they're really after how to replace *words* (eg, use of regex word boundaries) – Jon Clements Aug 19 '14 at 13:19
  • I know it is more than 3 years after your answer. I have a question: what if there were multiple instances of the target string, and I need only to replace a specific one? for instance, `s = "hello number 10, Agosto 19 if you like 10"`, I want to just substitute the second 10? – Heinz Nov 15 '17 at 18:31
  • @Heinz nothing out-of-the-box. You can implement something along this: https://stackoverflow.com/q/35091557/1190388 – hjpotter92 Nov 16 '17 at 03:16
2

If you don't know the number but know it is followed by a ,

import re
re.sub("\d+(?=,)","20",s) # one or more digits followed by a ,
hello number 20, Agosto 19

import re
re.sub("(\d+)","20",s,1) # first occurrence
hello number 20, Agosto 19
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321