0

Given a string and a pattern, Replace all the continuous occurrence of pattern with a single X in the string. For a clear view see the example below.

Input:

The first line of input contains an integer T denoting the number of test cases.
The first line of each test case is string str.
The second line of each test case contains a string s,which is a pattern.

Output:

Print the modified string str.

Constraints:

1 ≤ T ≤ 100
1 ≤ size of str,s ≤ 1000

Example:

Input

2
abababcdefababcdab
ab
geeksforgeeks
geeks

Output

XcdefXcdX
XforX

code:-

n = int(raw_input())
for i in range(n):
  x=raw_input()
  y=raw_input()
  x1=x.replace(y,"X")
  x2=""
  count=0
  for i in x1:
    if i=='X':
      if count==0:
        x2+=i
        count+=1
      else:
        count+=1
        ## do nothing         
    elif i!='X':
      count=0
      x2+=i
print (x2)
1
  • 1
    The original string might already contain "XX", in which case you don't want to replace this by just "X". Commented Feb 15, 2016 at 14:15

2 Answers 2

1

My answer to this question , first I replace all occurnce of substring with X and then replace all sequent X's with one X:

n = int(input())
for i in range(n):
    x = input()
    y = input()
    x1 = x.replace(y,"X")
    flag = False
    new_x1 = ""
    for i in x1:
        if i == "X" and flag == False:
            flag = True
            new_x1 += i
        elif i != "X" :
            flag = False
            new_x1 += i
    print (new_x1)

OutPut:

2
abababcdefababcdab
ab
#XcdefXcdX
geeksforgeeks
geeks
#XforX
Sign up to request clarification or add additional context in comments.

Comments

0

a simpler answer with regexp

import re
n = int(input())
for i in range(n):
    x = input()
    y = input()
    x1 = x.replace(y,"X")

    final = re.sub(r'(.)\1{1,}', r'\1', x1)
    print (final)

The regexp will replace any character (x) that occurs more than once

Comments

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.