There are python builtin methods for that.
It is also a good opportunity to remove the misleading Python 2 era _to_string terminology when the output is actually bytes.
Partial backport of electrum#5947
https://github.com/spesmilo/electrum/pull/5947/commits/2cf213552822b0feda4775ed94719679bcb1efb4
Depends on D16665