# Need a little help on this one I cannot find why I am getting WA
# https://www.spoj.com/problems/DIGSHIFT/
tests=int(input())
for test in range(1, tests+1):
print("Case " + str(test) + ":")
x = input()
y = [[x[0], 1]]
for i in range(1, len(x)):
if y[-1][0] == x[i]:
y[-1][1] += 1
else:
y.append([x[i], 1])
q = int(input())
for query in range(q):
d = input()
cnt = 0
l = len(y)
for i in range(0, l):
if d[0] == y[l-1-i][0]:
cnt += y[l-1-i][1]
del y[l-1-i]
y.append([d, cnt])
res = ''
for a in y:
res += a[0]*a[1]
print(int(res)%1000000007)