How to Convert String to Hex in Python?

As a Python developer with years of experience, I encountered a scenario where I needed to convert strings to hexadecimal when working with data encoding. In this article, I will walk you through multiple reliable methods to convert strings to hex in Python with practical examples, best practices, and performance considerations.

Convert String to Hex in Python

Let me explain some important methods for converting string to hex in Python.

Read Interfaces in Python

Method 1: Use str.encode() and hex()

The most simple approach to convert a string to hex in Python is to use the string’s encode() method to get a bytes representation, then apply the hex() method to convert those bytes to a hexadecimal string.

def string_to_hex(input_string):
    # First, encode the string to bytes
    bytes_data = input_string.encode('utf-8')

    # Then, convert bytes to hex
    hex_data = bytes_data.hex()

    return hex_data

# Example usage
original_text = "Hello, World!"
hex_result = string_to_hex(original_text)
print(hex_result) 

Output:

48656c6c6f2c20576f726c6421

You can see the output in the screenshot below.

python string to hex

This method is particularly effective because it first converts the string to its byte representation using UTF-8 encoding (which handles international characters well), then converts those bytes to hexadecimal.

Check out Access Modifiers in Python

Method 2: Use a Manual Approach with ord() and hex()

If you want more control over the process or need to understand the underlying mechanics, you can convert each character individually using the ord() function to get the Unicode code point, then convert it to hex with the hex() function in Python.

def string_to_hex_manual(input_string):
    hex_string = ""
    for character in input_string:
        # Get the Unicode code point
        code_point = ord(character)

        # Convert to hex and remove the '0x' prefix
        hex_value = hex(code_point)[2:]

        # Ensure two digits for each byte
        if len(hex_value) == 1:
            hex_value = "0" + hex_value

        hex_string += hex_value

    return hex_string

# Example usage
text = "Python"
hex_text = string_to_hex_manual(text)
print(hex_text) 

Output:

507974686f6e

You can see the output in the screenshot below.

string to hex python

This approach gives you a deeper understanding of how each character is converted to its hexadecimal representation. It’s also useful when you need special formatting or processing for each character.

Read How to Use Single and Double Quotes in Python?

Method 3: Use binascii.hexlify()

Python binascii module provides utilities for converting between binary and ASCII representations. The hexlify() function specifically converts binary data to its hexadecimal representation.

import binascii

def string_to_hex_binascii(input_string):
    # Convert string to bytes
    bytes_data = input_string.encode('utf-8')

    # Convert bytes to hex
    hex_data = binascii.hexlify(bytes_data)

    # Convert bytes back to string
    return hex_data.decode('ascii')

# Example usage
name = "Sarah Johnson"
hex_name = string_to_hex_binascii(name)
print(hex_name)

Output:

5361726168204a6f686e736f6e

You can see the output in the screenshot below.

convert string to hex python

The binascii.hexlify() function is particularly useful when working with binary data in Python’s standard library and offers good performance for larger strings.

Check out Python 3 vs Python 2

Method 4: Use List Comprehension for Concise Code

You can use list comprehension to create a more brief implementation:

def string_to_hex_comprehension(input_string):
    return ''.join([f'{ord(c):02x}' for c in input_string])

# Example usage
password = "P@ssw0rd!"
hex_password = string_to_hex_comprehension(password)
print(hex_password)  # Output: 50407373773072642100

This approach uses an f-string with the :02x format specifier to convert each character to a two-digit hexadecimal representation. It’s elegant and maintains good readability while being concise.

Method 5: Work with Non-ASCII and International Characters

When dealing with international characters or emojis, you need to be especially careful with encoding. Here’s how to handle these cases:

def string_to_hex_international(input_string):
    # Ensure proper encoding of international characters
    bytes_data = input_string.encode('utf-8')

    # Convert to hex and format as space-separated pairs
    hex_pairs = bytes_data.hex()

    # Optional: Format with spaces between bytes for readability
    formatted_hex = ' '.join(hex_pairs[i:i+2] for i in range(0, len(hex_pairs), 2))

    return formatted_hex

# Example with international characters
text_with_unicode = "Привет, World! 👋"
hex_unicode = string_to_hex_international(text_with_unicode)
print(hex_unicode)
# Output: d0 9f d1 80 d0 b8 d0 b2 d0 b5 d1 82 2c 20 57 6f 72 6c 64 21 20 f0 9f 91 8b

This method is particularly helpful when dealing with multilingual applications where you need to properly handle international character sets.

Read Difference Between “is None” and “== None” in Python

Compare Performance of all Methods

When working with large strings or in performance-critical applications, it’s important to choose the most efficient method. Here’s a comparison of the different approaches:

MethodAdvantagesDisadvantagesBest For
str.encode().hex()Simple, handles all charactersLess control over formattingGeneral-purpose use
Manual with ord()Full control, educationalVerbose, potentially slowerLearning, custom formatting
binascii.hexlify()Good performance, standard libraryRequires additional importLarge strings, binary data
List comprehensionConcise, readableSlightly less performantCode readability
With formattingBetter visualizationLarger output sizeDebugging, analysis

Examples and Use Cases

Let me explain some practical examples and use cases of converting string to hex in Python.

Example 1: Store Passwords Securely

In this example I will explain how to securely store passwords using SHA-256 hashing, which is a cryptographic algorithm commonly used for password security.

import hashlib

def hash_password(password):
    # Convert password to bytes
    password_bytes = password.encode('utf-8')

    # Create SHA-256 hash
    hash_obj = hashlib.sha256(password_bytes)

    # Get hex representation
    hex_digest = hash_obj.hexdigest()

    return hex_digest

# Example usage
user_password = "MySecurePassword123!"
hashed = hash_password(user_password)
print(f"Original: {user_password}")
print(f"Hashed (hex): {hashed}")

Hashing ensures passwords are not stored in plaintext, preventing attackers from directly seeing user credentials if a database is compromised.

Check out Compare Lists, Tuples, Sets, and Dictionaries in Python

Example 2: Work with Network Protocols

In this example, I will show how to convert a string into a MAC (Media Access Control) address format, which is used to identify network devices.

def format_mac_address(mac_string):
    # Convert string to hex
    hex_data = mac_string.encode().hex()

    # Format as MAC address (pairs of characters separated by colons)
    formatted_mac = ':'.join(hex_data[i:i+2] for i in range(0, len(hex_data), 2))

    return formatted_mac.upper()

# Raw MAC address data
device_id = "ZjQu"
mac = format_mac_address(device_id)
print(f"Formatted MAC: {mac}")  # Output: 5A:6A:51:75

MAC addresses are hardware addresses assigned to network interfaces

Read Is Python an Object-Oriented Language?

Conclusion

In this article, I explained how to convert strings to hex in Python. I discussed some methods such as using str.encode() and hex(), using ord() and hex(), using binascii.hexlify(), using list comprehension for concise cod, and working with non-ASCII and international characters. I also covered comparing the performances of all methods and some practical examples along with use cases.

You may read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.