re.sub function | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

re.sub function

We need to create a number formatting system for a contacts database. Create a program that will take the phone number as input, and if the number starts with "00", replace them with "+". The number should be printed after formatting. this is the question asked, but with my code it will replace all the zeroes in the number with a "+". so how can i make it just to check for the first two caracters of the number? #### import re num = input() zero = "00" new_num = re.sub(zero, "+", num) print(new_num) ####

4th Jan 2022, 1:59 PM
Ramiz Besic
Ramiz Besic - avatar
7 Answers
+ 4
You can use the string method startswith() to determine if the string starts with 00. If it does, construct a new string with + and the remaining characters. Using re without defining regular expression patterns seems a little overpowered to me – it can all be achieved with built-in functions
4th Jan 2022, 2:14 PM
Lisa
Lisa - avatar
+ 3
Jayakrishna🇮🇳 I think that would fail for "1230045" ("123+45") as it will replace 00 even if it isn't in the beginning of the string
4th Jan 2022, 2:17 PM
Lisa
Lisa - avatar
+ 3
In that case, as already know that match() checks at beginning then use that combined with sub() function. if re.match("00", num) : print(re.sub(zero, "+", num, 1) I think, those with basic samples from lesson, may it fail other cases. Not tested. OP should try..
4th Jan 2022, 2:26 PM
Jayakrishna 🇮🇳
+ 3
Yes, you are right! you need the count=1 parameter also! else it will anyway replace the other two zeroes. tanks
4th Jan 2022, 2:34 PM
Ramiz Besic
Ramiz Besic - avatar
+ 2
Ramiz Besic check "00120034" – you will still need the count=1 parameter as suggested by Jayakrishna🇮🇳
4th Jan 2022, 2:26 PM
Lisa
Lisa - avatar
+ 1
thanks for your help. worked with this one: import re num = input() zero = "00" if num.startswith(zero): print(re.sub(zero, "+", num)) else: print(num)
4th Jan 2022, 2:24 PM
Ramiz Besic
Ramiz Besic - avatar
0
Use count= 1 as parameter to sub function. new_num = re.sub(zero, "+",num,1) Syntax is : sub(pattern, replace, string, count=0, flag=0) have default values for count and flags
4th Jan 2022, 2:12 PM
Jayakrishna 🇮🇳