在 Python 3 中删除字符串文字前面的 'b' 字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37016946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove 'b' character do in front of a string literal in Python 3
提问by Panagiotis Drakatos
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'
采纳答案by Pythonista
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:
修复:
- You can just print the string first
- Redundantly decode it after encoding
- 您可以先打印字符串
- 编码后冗余解码
回答by krock
This should do the trick:
这应该可以解决问题:
pw_bytes.decode("utf-8")
回答by Muhammad Younus
Here u Go
你来了
f = open('test.txt','rb+')
ch=f.read(1)
ch=str(ch,'utf-8')
print(ch)