123

I am new in python programming and i am a bit confused. I try to get the bytes from a string to hash and encrypt but i got

b'...'

b character in front of string just like the below example. Is any way avoid this?.Can anyone give a solution? Sorry for this silly question

import hashlib

text = "my secret data"
pw_bytes = text.encode('utf-8')
print('print',pw_bytes)
m = hashlib.md5()
m.update(pw_bytes)

OUTPUT:

 print b'my secret data'
Panagiotis Drakatos
  • 2,851
  • 4
  • 31
  • 43

3 Answers3

270

This should do the trick:

pw_bytes.decode("utf-8")
krock
  • 28,904
  • 13
  • 79
  • 85
36

Here u Go

f = open('test.txt','rb+')
ch=f.read(1)
ch=str(ch,'utf-8')
print(ch)
Muhammad Younus
  • 1,896
  • 19
  • 20
21

Decoding is redundant

You only had this "error" in the first place, because of a misunderstanding of what's happening.

You get the b because you encoded to utf-8 and now it's a bytes object.

 >> type("text".encode("utf-8"))
 >> <class 'bytes'>

Fixes:

  1. You can just print the string first
  2. Redundantly decode it after encoding
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
Pythonista
  • 11,377
  • 2
  • 31
  • 50
  • 38
    why is this the accepted answer? It's the one below that is. This one is too much talk...The answer below by krock is the answer. And by the way, str(x) does not remove the b – daparic Mar 09 '18 at 14:53
  • 3
    First answers with no explanation or as you put it "talk" are useless. Code only answers are frowned upon here. Second, I didn't say str(x) removed the b. – Pythonista Mar 09 '18 at 15:30
  • 11
    This does not answer the question. – ThaJay Oct 15 '19 at 13:26
  • 2
    *this not an answer !* – dsgdfg Jul 14 '20 at 11:32
  • @dsgdfg Just because you didnt understand it doesnt mean its not an answer. It just means you come to stackoverflow looking for copy paste code without acually knowing what youre doing or attempting to understand even a modicum of the code you write. How much simpler are you looking for than a 50 character 2 bullet point itemization of how you screwed up? – Pythonista Jul 14 '20 at 18:00