在Python 3中删除字符串文字前面的'b'字符

时间:2021-09-07 20:19:13

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

我是python编程的新手,我有点困惑。我尝试从字符串中获取字节以进行哈希和加密,但我得到了

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

b字符串前面的字符就像下面的例子一样。有没有办法避免这种情况?。任何人都可以提供解决方案吗?对不起这个愚蠢的问题

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'

3 个解决方案

#1


8  

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.

你得到了b因为你编码为utf-8而现在它是一个字节对象。

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

Fixes:

  1. You can just print the string first
  2. 您可以先打印字符串

  3. Redundantly decode it after encoding
  4. 编码后冗余解码

#2


66  

This should do the trick:

这应该是诀窍:

pw_bytes.decode("utf-8")

#3


10  

Here u Go

你去吧

f = open('test.txt','rb+')
ch=f.read(1)
ch=str(ch,'utf-8')
print(ch)

#1


8  

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.

你得到了b因为你编码为utf-8而现在它是一个字节对象。

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

Fixes:

  1. You can just print the string first
  2. 您可以先打印字符串

  3. Redundantly decode it after encoding
  4. 编码后冗余解码

#2


66  

This should do the trick:

这应该是诀窍:

pw_bytes.decode("utf-8")

#3


10  

Here u Go

你去吧

f = open('test.txt','rb+')
ch=f.read(1)
ch=str(ch,'utf-8')
print(ch)