什么是变量上的 b'string' 的等价物? [英] What is the equivalent to b'string' on a variable?
问题描述
我需要在使用之前对一串文本进行编码,但唯一的问题是它是一个变量,我所知道的是通常我会使用 b'string'.我假设我会使用 variable.encode(),但我会使用什么编码?
I need to encode a string of text before using it, but the only problem is it is a variable and all I know is that normally I would use b'string'. I assume I would use variable.encode(), but what encoding would I use?
抱歉,我误解了这个问题,Christian 的回答帮助我意识到发生了什么.感谢大家的帮助.
Sorry, I misunderstood the issue and Christian's answer helped me realize what was going on. Thanks to everyone for helping.
推荐答案
好吧,您必须决定使用哪种编码.您可以使用 UTF-8 作为合理的默认值,也可以从环境中推断编码.
Well, you have to decide which encoding to use. You can either go with UTF-8 as a sensible default, or infer the encoding from the environment.
环境可以是,例如:
- HTTP 连接中的 Content-Type 标头
- UNIX 系统上的 LANG/LC_CTYPE 变量
sys.getfilesystemencoding()
函数
然后您可以通过 var.encode(encoding)
.
You can then transform your Unicode variable into a bytes string via var.encode(encoding)
.
另请查看Python Unicode HOWTO.
这篇关于什么是变量上的 b'string' 的等价物?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!