I'm using web3.py v4.x and I have an issue to convert string to bytes32. First I checked out Web3.py conversion APIs. So I used Web3.toBytes but still not working. Kindly check out the below error for more details:

Could not identify the intended function with name `publish`, positional argument(s) of type `(<class 'int'>, <class 'bytes'>, <class 'bytes'>)` and keyword argument(s) of type `{}`.
Found 1 function(s) with the name `publish`: ['publish(uint256,bytes32,bytes32)']
Function invocation failed due to improper argument encoding.
  • 1
    Can you show what re you doing?
    – Jaime
    Jun 11, 2018 at 11:56
  • You probably want Web3.toHex(text='my text').
    – user19510
    Jun 11, 2018 at 12:18
  • Thanks for your comment, but the data types uses bytes32. Hex didn't work!
    – 0x3bfc
    Jun 11, 2018 at 12:50

1 Answer 1


Simply data.encode('utf-8') should be sufficient, if you are converting a string to bytes data.

If your string is more than 32 bytes long after encoding to UTF-8, then your problem is that your contract can't accept the data you want to send.

More background

If a function takes a bytes32, it cannot accept a value longer than 32 bytes. Web3.py will actually reject the function as a possibility based on the type mismatch (because multiple functions with the same name and different types are allowed).

If you have more than 32 bytes to send in, you probably don't want to blindly clip off the end. What you need to do will be highly dependent on the semantics of the contract that you are interacting with.

You do not need to pad the value, Web3.py will handle that for you.

Finally, bytes(str_data, 'utf-8') is equivalent to str_data.encode('utf-8'). Which you prefer is a matter of taste, I suppose, and potentially performance.

  • 1
    thanks ... the problem was I'm using byte code longer than 32 bytes. this was the issue. It is solved now.
    – 0x3bfc
    Jun 13, 2018 at 11:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.