binascii.b2a vs ord()

Chris Angelico rosuav at gmail.com
Sat Jan 9 22:37:09 EST 2021


On Sun, Jan 10, 2021 at 2:31 PM Bischoop <Bischoop at vimart.net> wrote:
>
> I wanted to learn about conversion string to Ascii.
> So I learn about binascii.b2a but because the output wasn't what I
> wanted got deeper and found out about ord(c) and actually that's what
> I'expected.
> So what's that binascii and why I cant convert ascii that I got from ord
> to string by using char, instead I'm getting some strings in weird
> coding.
>
>
> import binascii
> Ttext = b'This is a string'
> text2 = 'This is a string'
> data = binascii.b2a_uu(text)
> print(f' Conversion byte string to ascii by binascii:\n {data}')
> res = ' '.join(format(ord(i), 'b') for i in text2)
> print(f'Conversion string to Ascii by ord:\n {res}')
>
> b = binascii.a2b_uu(data)
> print(f' Conversion ascii to String by binascii:\n {b}')
> k= res.split(' ')
> for i in k:
>    w= k.index(i)
>    k[w]= int(i)
>
> c = ' '.join(chr(int(val)) for val in res.split(' '))
> print(f'Conversion Ascii to string by chr: \n {c}')
>
>
> #output:
> Conversion byte string to ascii by binascii:
>  b"05&AI<R!I<R!A('-T<FEN9P  \n"
> Conversion string to Ascii by ord:
>  1010100 1101000 1101001 1110011 100000 1101001 1110011 100000 1100001 100000 1110011 1110100 1110010 1101001 1101110 1100111
>  Conversion ascii to String by binascii:
>  b'This is a string'
> Conversion Ascii to string by chr:
>  󶦴 􌳈 􌳉 􎿻 𘚠 􌳉 􎿻 𘚠 􌣡 𘚠 􎿻 􏁔 􎿺 􌳉 􌴶 􌥏
>

Trace it through, step by step. You have a series of ASCII values,
represented in binary, and then you call int() on each of them. What
sort of numbers will you get?

Then look at what chr() does when given those sorts of numbers.

BTW, it may be helpful to look at the repr of the final string, rather
than simply printing it out. (It also may be unhelpful. If so, don't
worry about it.)

Have fun!

ChrisA


More information about the Python-list mailing list