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.

3
  • 2
    have you tried anything? Where you got stuck? Commented Aug 19, 2014 at 13:13
  • Yes, you can do that using re.sub. Commented Aug 19, 2014 at 13:14
  • 2
    "hello number 10, Agosto 19".replace("10","20") Commented Aug 19, 2014 at 13:17

3 Answers 3

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'
Sign up to request clarification or add additional context in comments.

Comments

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')

3 Comments

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)
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 nothing out-of-the-box. You can implement something along this: stackoverflow.com/q/35091557/1190388
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

1 Comment

Your lookahead is incorrect. It should be \d+(?=,)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.