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:
48656c6c6f2c20576f726c6421You can see the output in the screenshot below.

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:
507974686f6eYou can see the output in the screenshot below.

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:
5361726168204a6f686e736f6eYou can see the output in the screenshot below.

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: 50407373773072642100This 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 8bThis 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:
| Method | Advantages | Disadvantages | Best For |
|---|---|---|---|
| str.encode().hex() | Simple, handles all characters | Less control over formatting | General-purpose use |
| Manual with ord() | Full control, educational | Verbose, potentially slower | Learning, custom formatting |
| binascii.hexlify() | Good performance, standard library | Requires additional import | Large strings, binary data |
| List comprehension | Concise, readable | Slightly less performant | Code readability |
| With formatting | Better visualization | Larger output size | Debugging, 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:75MAC 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:
- JavaScript vs Python for Web Development: Choosing the Right for Your Project
- Is Python a High Level Language?
- Is Python a High Level Language?

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.