python - How to encode a string in a SQL CHAR -
'admin'
encoded = char(97, 100, 109, 105, 110)
i know if there module or way convert each letter of string sql char
s. if not, how convert myself? have access chart says a=97, b=98, etc., if helps.
i'm not sure why need @ all. it's not hard string representation of char
field holding ascii or unicode or whatever code points. i'm pretty sure don't need that, because databases know how compare strings passed in sql, etc. unless you're trying to, say, generate dump looks ones other tool. but, assuming do need this, here's how.
i think you're looking ord
function:
given string representing 1 unicode character, return integer representing unicode code point of character. example, ord('a') returns integer 97 , ord('\u2020') returns 8224. inverse of chr().
this works because python has access same chart have—in fact, bunch of different ones, 1 each encoding knows about. in fact, chart pretty encoding is.
so, example:
def encode_as_char(s): return 'char({})'.format(', '.join(str(ord(c)) c in s))
or, if wanted list of numbers, not string made out of numbers, it's simpler:
def encode_as_char(s): return [ord(c) c in s]
this assuming either (a) database storing unicode characters , you're using python 3, or (b) database storing 8-bit characters , you're using python 2. otherwise, need encode
or decode
step in there well.
for python 3 unicode string utf-8 database (notice don't need ord
here, because python 3 bytes
sequence of numbers):
def encode_as_utf8_char(s): return 'char({})'.format(', '.join(str(c) c in s.encode('utf-8')))
for python 2 utf-8 string unicode database:
def encode_utf8_as_char(s): return 'char({})'.format(', '.join(str(ord(c)) c in s.decode('utf-8')))
Comments
Post a Comment