SoFunction
Updated on 2025-04-11

How to convert str, bytes, and hexadecimal strings in python

Preface

In Python,str(String),bytesConversion between (byte sequences) and hexadecimal strings (usually in string form, but the content represents a hexadecimal number) is a very common operation. Here we will explain in detail how to convert between them.

1. Conversion from str  to bytes

Tostr(String) Convert tobytes(byte sequence), can be usedstrof.encode()method. This method uses UTF-8 encoding by default to convert strings into byte sequences.

s = "hello"  
b = ('utf-8')  # Encoding with UTF-8print(b)  # Output: b'hello'

If the string contains non-ASCII characters, make sure to use the correct encoding to avoidUnicodeEncodeError

2. Conversion from bytes to str

Willbytes(byte sequence) convert backstr(String), can be usedbytesof.decode()method. This method also uses UTF-8 encoding by default.

b = b'hello'  
s = ('utf-8')  
print(s)  # Output: hello

ifbytesThe data is not encoded in UTF-8, you need to specify the correct encoding to avoidUnicodeDecodeError

3. Conversion of hexadecimal string represented by str to bytes

If there is a hexadecimal string (i.e., the character in the string is a hexadecimal number, such as"48656c6c6f"express"hello"), can be used()Method converts it tobytes

hex_str = "48656c6c6f"  
b = (hex_str)  
print(b)  # Output: b'hello'

4. Conversion of bytes to hexadecimal string (str)

WillbytesConvert to hexadecimal string, can be usedbytesof.hex()method.

b = b'hello'  
hex_str = ()  
print(hex_str)  # Output: 48656c6c6f

Summarize

  • use.encode()WillstrConvert tobytes
  • use.decode()WillbytesConvert tostr
  • use()Put a hexadecimal string (str) Convert tobytes
  • use.hex()WillbytesConvert to hexadecimal string (str)。

Note: When performing encoding and decoding operations, make sure to use the correct character encoding (such as UTF-8) to avoid encoding errors.

This is the article about the mutual conversion methods between str, bytes, and hexadecimal strings in python. For more related contents of str, bytes, and hexadecimal strings in python, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!