Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

You can do something similar in Python:

    utf8_bytes: bytes = bytes(input_string, encoding="utf-8")
    
    # Perform the conversion from one encoding to the other.
    unicode_string: str = str(utf8_bytes, encoding="utf-8")
    ascii_bytes: bytes = bytes(unicode_string, encoding="ascii")
    
    # The conversion could also be written as:
    ascii_bytes: bytes = utf8_bytes.decode("utf-8").encode("ascii")
    
    output_string: str = str(ascii_bytes, encoding="ascii")
The biggest difference is that the conversion step requires you to explicitly decode the bytes to a unicode string and then encode the unicode string back to bytes rather than providing a convert() method that does this internally.

Perhaps a convenience method would be nice, something like this, but it somewhat obscures the intermediate decode-to-unicode step:

    ascii_bytes: bytes = utf8_bytes.convert(to_encoding="ascii")


Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: