Replacing a string with a substring

I have a List:
DUP1 DUP1 DUP1 DUP1 DUP1 DUP2 DUP2 DUP2DUP2 JUMPDEST JUMPDEST JUMPDEST
I want to replace, DUP1 and DUP2 with DUP and similarly other matching strings with their sub strings.
I have written the following code:

changeOpcodes= ["DUP", "SWAP", "PUSH"]
lengthOfOpcodeList = len(opcodeList)
for x in range(1,lengthOfOpcodeList):
    str = opcodeList[x]
    if (str.find(changeOpcodes[0]) >0):
        print("Str0 =", str)
        opcodeList[x] = changeOpcodes[0]
    elif (str.find(changeOpcodes[1]) >0):
        print("Str1 =", str)
        opcodeList[x] = changeOpcodes[1]
    elif (str.find(changeOpcodes[2]) >0):
        print("Str0 =", str)
        opcodeList[x] = changeOpcodes[2]

Right now I am not getting any error but code is not executing the statements:
opcodeList[x] = changeOpcodes[0]
or
opcodeList[x] = changeOpcodes[1]
or
opcodeList[x] = changeOpcodes[2]

Thus when I am printing the list:

for w in opcodeList:
   print(w)

I am still getting DUP1, DUP2, DUP3,…SWAP1, SWAP2,…PUSH1, PUSH2,…

Somebody please guide me.
Zulfi.

Hi @Zulfi6000, with matching you mean simply checking if one is a substring of the other? Currently you’re checking if the string matches after the first character; indexes are zero-based, and if there’s no match find() will return -1. But you might actually just use the in operator instead:

opcode_list = ['DUP1', 'DUP2', 'SWAP1', 'DUP1', '4SWAP']
change_opcodes = ['DUP', 'SWAP', 'PUSH']

for index, opcode in enumerate(opcode_list):
    for change in change_opcodes:
        if change in opcode:
            opcode_list[index] = change
            continue

print(opcode_list)  # ['DUP', 'DUP', 'SWAP', 'DUP', 'SWAP']
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.