str = 'xyzA*12*pqR*stB*HS*lmN*opA*45*a4N*gB*SD*drtU*ghy'
result = ''
start = 0
while str.find('A*', start) > -1:
    aStart = str.find('A*', start) + 2
aEnd = str.find('*', aStart)
bStart = str.find('B*', aEnd) + 2
bEnd = str.find('*', bStart)
result += str[start:aStart] + str[bStart:bEnd] + str[aEnd:bStart] + str[aStart
    :aEnd]
start = bEnd
result += str[start:]
print(result)
How to switch two elements in string using Python RegEx?