给定字符串和模式,用字符串中的单个X替换所有连续出现的模式。要获得清晰的视图,请参阅下面的示例。
输入:
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.
输出:
Print the modified string str.
约束:
1 ≤ T ≤ 100
1 ≤ size of str,s ≤ 1000
示例:
输入
2
abababcdefababcdab
ab
geeksforgeeks
geeks
输出
XcdefXcdX
XforX
代码: -
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)
答案 0 :(得分:1)
我对这个问题的回答,首先我用X
替换所有子串的出现,然后用一个X
替换所有后续的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)
输出:
2
abababcdefababcdab
ab
#XcdefXcdX
geeksforgeeks
geeks
#XforX
答案 1 :(得分:0)
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)
正则表达式将替换多次出现的任何字符(x)