Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent to b'string' on a variable?

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?

EDIT: Sorry, I misunderstood the issue and Christian's answer helped me realize what was going on. Thanks to everyone for helping.

like image 824
diodepain Avatar asked Oct 21 '25 21:10

diodepain


1 Answers

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.

The environment can be, for example:

  • The Content-Type header in HTTP connections
  • The LANG/LC_CTYPE variables on UNIX systems
  • The sys.getfilesystemencoding() function

You can then transform your Unicode variable into a bytes string via var.encode(encoding).

Also check out the Python Unicode HOWTO.

like image 76
Christian Aichinger Avatar answered Oct 23 '25 10:10

Christian Aichinger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!