Richard21
Richard21

Reputation: 157

Convert each element of a list to sha256

I would like to know how to convert each element of a list to sha256 and get the values inside another list. The data I'm using is:

lst=['Under.csv', 'Upper.csv', 'Below.csv', 'Outside.csv', 'Inside.csv', 'Out.csv', 'in.xlsx', 'water.xlsx', 'sun.xlsx']

I'm triying to use list comprehesion:

lst1=[hashlib.sha256(b"i").hexdigest().upper() for i in lst]

But I'm just getting the first sha256 of the first element repeated.

Also:

lst2=[hashlib.sha256("{}".format(b'i')).hexdigest().upper() for i in lst]

And with this other one I get an error:

AttributeError: 'bytes' object has no attribute 'format'

How can I solve this issue and get the sha256 of each element inside another list in the same order as the stings in lst?.

The output of lst1 is:

['DE7D1B721A1E0632B7CF04EDF5032C8ECFFA9F9A08492152B926F1A5A7E765D7', 'DE7D1B721A1E0632B7CF04EDF5032C8ECFFA9F9A08492152B926F1A5A7E765D7', 'DE7D1B721A1E0632B7CF04EDF5032C8ECFFA9F9A08492152B926F1A5A7E765D7', 'DE7D1B721A1E0632B7CF04EDF5032C8ECFFA9F9A08492152B926F1A5A7E765D7', 'DE7D1B721A1E0632B7CF04EDF5032C8ECFFA9F9A08492152B926F1A5A7E765D7', 'DE7D1B721A1E0632B7CF04EDF5032C8ECFFA9F9A08492152B926F1A5A7E765D7', 'DE7D1B721A1E0632B7CF04EDF5032C8ECFFA9F9A08492152B926F1A5A7E765D7', 'DE7D1B721A1E0632B7CF04EDF5032C8ECFFA9F9A08492152B926F1A5A7E765D7', 'DE7D1B721A1E0632B7CF04EDF5032C8ECFFA9F9A08492152B926F1A5A7E765D7']

As I said I just get the first value repeated.

Upvotes: 0

Views: 680

Answers (2)

Elyassaf Shoham
Elyassaf Shoham

Reputation: 81

In your first example you are passing the string "i" to the function.

You should use something like this: [hashlib.sha256(i.encode()).hexdigest().upper() for i in lst]

here you pass the value of i encoded.

Upvotes: 1

Harshana
Harshana

Reputation: 5476

You get the same value because you use the same string inside the hashlib.sha256() function. You need to pass i as variable. Try passing the variable correctly and encoding it

code:

lst1=[hashlib.sha256(i.encode()).hexdigest().upper() for i in lst]

Upvotes: 1

Related Questions