[英]How do I turn a Python string stored in a variable into a byte sequence?
Very simple, I know, but the docs aren't too helpful. 很简单,我知道,但文档并没有太大帮助。 I'm trying to hash a simple string.
我正在尝试哈希一个简单的字符串。 I was following this guide.
我正在遵循这个指南。 The example given therein is:
其中给出的例子是:
import hashlib
hash_object = hashlib.md5(b'Hello World')
print(hash_object.hexdigest())
And then you have a hash representation. 然后你有一个哈希表示。 Suppose I want to take this one step further.
假设我想更进一步。 I have four strings I want to concatenate together, the result of which needs to be converted to byte sequence, in order to be passed to the
hashlib.md5()
function. 我有四个字符串要连接在一起,其结果需要转换为字节序列,以便传递给
hashlib.md5()
函数。 However, I'm curious how I can replicate the b'Hello World'
syntax using a variable instead of a hard-coded string. 但是,我很好奇我如何使用变量而不是硬编码字符串来复制
b'Hello World'
语法。 Docs seem to suggest you can pass in a format to the built-in format function, so for my use-case something like: 文档似乎建议您可以将格式传递给内置格式函数,因此对于我的用例,例如:
my_string = '%s%s%s%s' % (first, second, third, fourth)
byte_string = format(my_string, 'b')
This doesn't quite work, though. 但这并不是很有效。 How do I do this?
我该怎么做呢?
Strings in Python are a sequence of characters, to convert a string to a sequence of bytes you encode it using some character set. Python中的字符串是一系列字符,用于将字符串转换为使用某些字符集对其进行编码的字节序列。 For example:
例如:
my_string = '%s%s%s%s' % (first, second, third, fourth)
byte_string = my_string.encode('utf-8')
Instead of my_string.encode('utf-8')
you could also use bytes(my_string, 'utf-8')
, these are equivalent. 你也可以使用
bytes(my_string, 'utf-8')
代替my_string.encode('utf-8')
bytes(my_string, 'utf-8')
,它们是等价的。 You can also use a different encoding if you like, but UTF-8 is generally a good choice because it is capable of representing any code point (character) and it is fairly compact, especially for ASCII data. 如果您愿意,也可以使用不同的编码,但UTF-8通常是一个不错的选择,因为它能够表示任何代码点(字符)并且相当紧凑,特别是对于ASCII数据。
my_string = '%s%s%s' % (first, second, third, fourth)
byte_string = bytes(my_string)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.