-4

I am stuck on this writing the chunk of code in Python that converts each character in the string to its decimal and binary number representation. For example, if the user would input the word "bad", the program needs to output the decimal and binary number representation for "b" "a" "d".

Required decimal representation of "b" "a" "d" is 1 0 3 and required binary representation of "b" "a" "d" is 00001 00000 00011.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • What's the "decimal and binary number representation" of "b" "a" "d"? – L3viathan Jan 17 '18 at 18:49
  • 4
    Welcome to Stack Overflow. This is not a code/SQL/regex writing service, where you post a list of your requirements and language of choice and a code monkey churns out code for you. We're more than happy to help, but we expect you to make an effort to solve the problem yourself first. Once you've done so, you can explain the problem you're having, include the **relevant** portions of your work, and ask a specific question, and we'll try to help. Good luck. – Ken White Jan 17 '18 at 18:50
  • Decimal representation of "b" "a" "d" is 1 0 3. Binary representation of "b" "a" "d" is 00001 00000 00011. – Jacob Gellhaus Jan 17 '18 at 18:52

1 Answers1

2

ord gets you the code of each character. Map that with a proper format string and you're done:

s = "bad"

print(["{0} {0:b}".format(ord(c)) for c in s])

prints:

['98 1100010', '97 1100001', '100 1100100']

ignoring the code offset (by subtracting the code of a) & using more formatting (zero-padded 5-digit binary):

["{0} {0:05b}".format(ord(c)-ord('a')) for c in s]

you get:

['1 00001', '0 00000', '3 00011']
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219