Home > other >  How to extract a word from a string in python
How to extract a word from a string in python

Time:03-09

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'>

CodePudding user response:

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])

CodePudding user response:

Split using space, take the second element, split using parenthesis and take the first element

text = "<Function approve(address,uint256)>"
print(text.split(" ")[1].split("(")[0])


approve

CodePudding user response:

You can use split:

txt = "<Function balanceOf(address)>"

txt.split()[1].split('(')[0]

CodePudding user response:

Something like this seems to work:

functions = [func[:-1] for func in "".join(allFunctions).split('<Function ')][1:]
  • Related