create a md5 hash from a string in python

To create an MD5 hash from a string in Python, you can use the hashlib module. Here's an example:

main.py
import hashlib

# define string
string = "Hello, world!"

# encode the string in utf-8 format
encoded_str = string.encode('utf-8')

# hash the encoded string with MD5 hash
md5_hash = hashlib.md5(encoded_str).hexdigest()

# print the MD5 hash
print(f"The MD5 hash of the string '{string}' is: {md5_hash}")
305 chars
14 lines

Output:

main.py
The MD5 hash of the string 'Hello, world!' is: b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9
112 chars
2 lines

In this example, we first define our string and then use the encode() method to convert it to bytes in the UTF-8 format. Next, we use the hashlib.md5() method to create an MD5 hash object and pass in the encoded string as a parameter. Finally, we use the hexdigest() method to get the hexadecimal representation of the MD5 hash.

gistlibby LogSnag