Search code examples
pythonstringethereumweb3py

How to extract a word from a string in python


Im getting functions from a smart contract in this format I print them out in a loop:

allFunctions = contract.all_functions()
for text in allFunctions:
      print(text)

<Function approve(address,uint256)>
<Function balanceOf(address)>
<Function burn(uint256)>
<Function burnFrom(address,uint256)>
<Function decimals()>
<Function decreaseAllowance(address,uint256)>
<Function increaseAllowance(address,uint256)>
<Function mint(address,uint256)>
<Function name()>
<Function owner()>
<Function pause()>
<Function paused()>
<Function renounceOwnership()>
<Function symbol()>

Now I want to dynamically remove everything from this string so Im only left with the actual function name which is approve balanceOf,name, owner pause etc...

I need to do this manually since a lot of smart contracts have different function names

So I can not use strip("<function ()>") Any ideas on how I can solve this?

The ouptut type I get is

<class 'web3._utils.datatypes.allowance'>

Solution

  • Assuming all data in a string, you can use regex:

    import re
    
    a = '''<Function approve(address,uint256)>
    <Function balanceOf(address)>
    <Function burn(uint256)>
    <Function burnFrom(address,uint256)>
    <Function decimals()>
    <Function decreaseAllowance(address,uint256)>
    <Function increaseAllowance(address,uint256)>
    <Function mint(address,uint256)>
    <Function name()>
    <Function owner()>
    <Function pause()>
    <Function paused()>
    <Function renounceOwnership()>
    <Function symbol()>'''
    
    re.findall("Function (.*)\(.*\)", a)
    

    edit:

    import re
    
    allFunctions = contract.all_functions()
    for text in allFunctions:
          print(re.findall("Function (.*)\(.*\)", text.__str__())[0])