HackerRank Regex Substitution solution in Python YASH PAL, 31 July 202417 January 2026 HackerRank Regex Substitution solution in Python – In this Hackerrank Regex substitution problem in Python programming. The re.sub() tool (sub stands for substitution) evaluates a pattern and, for each valid match, it calls a method (or lambda).The method is called for all matches and can be used to modify strings in different ways.The re.sub() method returns the modified string as an output.Learn more about re.sub(). Transformation of StringsCodeimport re #Squaring numbers def square(match): number = int(match.group(0)) return str(number**2) print re.sub(r"\d+", square, "1 2 3 4 5 6 7 8 9") Output 1 4 9 16 25 36 49 64 81 Replacements in StringsCodeimport re html = """ <head> <title>HTML</title> </head> <object type="application/x-flash" data="your-file.swf" width="0" height="0"> <!-- <param name="movie" value="your-file.swf" /> --> <param name="quality" value="high"/> </object> """ print re.sub("(<!--.*?-->)", "", html) #remove comment Output<head> <title>HTML</title> </head> <object type="application/x-flash" data="your-file.swf" width="0" height="0"> <param name="quality" value="high"/> </object> TaskYou are given a text of N lines. The text contains && and || symbols.Your task is to modify those symbols to the following:&& → and || → or Both && and || should have a space ” ” on both sidesHackerrank Regex Substitution problem solution in Python 2.import re n = int(raw_input()) for _ in range(0, n): line = raw_input() line = re.sub(r' [&]{2,2} ', ' and ', line) line = re.sub(r' [|]{2,2} ', ' or ', line) line = re.sub(r' [&]{2,2} ', ' and ', line) line = re.sub(r' [|]{2,2} ', ' or ', line) print(line)Regex Substitution problem solution in Python 3.import re ii = int(input()) for i in range(0,ii): txt = input() txt = re.sub(r" && "," and ",txt) txt = re.sub(r" || "," or ",txt) txt = re.sub(r" && "," and ",txt) txt = re.sub(r" || "," or ",txt) print(txt)Problem solution in pypy programming.# Enter your code here. Read input from STDIN. Print output to STDOUT import sys import re pat = re.compile(r'''(?<= )(&&|||)(?= )''', re.U|re.I|re.M|re.S) for idx in range(int(raw_input())): l = raw_input() if pat.search(l): print(pat.sub(lambda m: 'and' if m.group(1) =='&&' else 'or', l)) else: print(l)Problem solution in pypy3 programming.import re for _ in range(int(input())): str_ = input() str_ = re.sub(r"(?<= )(&&)(?= )", "and", str_) print(re.sub(r"(?<= )(||)(?= )", "or", str_)) coding problems solutions Hackerrank Problems Solutions Python Solutions HackerRankPython