views:

124

answers:

3

Hello everyone I'm currently new to python, and I'm trying to write a program where the user can input a message and the output will show the numeric code of the message, but at the same time I need to write the numeric code to an additional file.

So for example the user inputs the word "Hello" The user will see the output "72 101 108 108 111"

Now that output should also be copied into an external document labeled as my "EncryptedMessage.txt"

The numbers are written to the folder however there is no space between them so when I put it in the decoder it will not decode, is there anyway for me to get a space between them?

Example of my coding.

def main():

    outfile = open("EncryptedMessage.txt", "w")
    messgage = " "

    message = raw_input("Enter a message: ")
    for ch in message:
        ascii = ord(ch)

        outfile.write(str(ascii) )

        print ascii,


    outfile.close()

Sorry I'm not really good with programming terms.

+1  A: 

just manually add a space:

outfile.write(str(ascii) + " ")
cobbal
A: 

Bear in mind that cobbal's answer will add an extra space to the end of the file. You can strip it off using:

s.rstrip(str(ascii))
Phillip Knauss
Thank you cobbal, and Phillip for the answers.I figured it had to be something simple I was missing out on!
Ray
+4  A: 

You can do this without the loop using Python list comprehension and the join method to add the spaces between the ascii values.

" ".join([str(ord(c)) for c in message])

This will evaluate to a string of ascii values separated by spaces.

tarn
this is probably the better way of doing it. Just a note though, the square brackets are unnecessary as join will accept an iterator
cobbal
@cobbal good point
tarn