1

Using Python 3.4, I am trying to convert a string to padded ASCII values (for each character).

Given a sting:

myString = "hello world"

Convert each character to ASCII and join back into a single string:

asciiString = ''.join(str(ord(c)) for c in myString)

This works great, returning:

'10410110810811132119111114108100'

I would like to pad EACH CHARACTER to 7 digits and then join. I've been trying to do this with format and have tried so many combinations of join, format, str, and ord that I can't even list them all. Can someone please help me figure out how to add format to the "asciiString =" line? Maybe this can't be done in a single line of code?

CDspace
  • 2,551
  • 17
  • 31
  • 35
seveninstl
  • 793
  • 1
  • 8
  • 15
  • Please update your question with your expected output. – quamrana Nov 15 '17 at 20:39
  • "h" = 104 (first 3 digits of the returned string). I would like it to return 0000104. "e" = 101. I would like it to return 0000101. So that the string "he" would return 00001040000101 instead of 104101. – seveninstl Nov 15 '17 at 20:44
  • 1
    Possible duplicate of [How can I fill out a Python string with spaces?](https://stackoverflow.com/questions/5676646/how-can-i-fill-out-a-python-string-with-spaces) – quamrana Nov 15 '17 at 20:47
  • Possible duplicate of [Nicest way to pad zeroes to string](https://stackoverflow.com/questions/339007/nicest-way-to-pad-zeroes-to-string) ... quite possible. – atru Nov 15 '17 at 20:50
  • I looked at both of the suggested Stack Overflow questions above, along with many others. (I searched for 6 hours). I continued to get errors with my syntax. Joald's answer worked perfectly! – seveninstl Nov 15 '17 at 20:58

1 Answers1

1
asciiString = ''.join(str('{num:07d}'.format(num=ord(c))) for c in myString)
Joald
  • 954
  • 8
  • 23