Welcome, guest | Sign In | My Account | Store | Cart

Converts a string of characters to ascii

Python, 13 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
def encrypt(string):
    a = string
    new_string = ''
    for x in a:
        new_string = new_string+str(ord(x))+' '
    return new_string
def unencrypt(string):
    a = string
    new_string = ''
    b = a.split()
    for x in b:
        new_string = new_string+chr(int(x))
    return new_string

4 comments

David Lambert 15 years, 6 months ago  # | flag

To learn about character encodings check out the pyzine article:

http://www.pyzine.com/Issue008/Section_Articles/article_Encodings.html
Daniel Lepage 15 years, 6 months ago  # | flag

This would be slightly faster and slightly shorter if you used list comprehensions and ''.join instead of assembling the string yourself, as in:

def encrypt(string):
    return ' '.join([str(ord(x)) for x in string])
Gahl Saraf 15 years, 6 months ago  # | flag

Faster still is removing the list comprehension and using an inline generator:

def encrypt(string):
    return ' '.join(str(ord(x)) for x in string)

And better yet - faster by a factor of four and far more efficient space-wise - use base64 conversion for this:

import base64
def encrypt(string):
    return base64.b64encode(string)
Aaron Gallagher 15 years, 5 months ago  # | flag

@Gahl Saraf

Generator expressions are slower than list comprehensions because there's more overhead involved. List comprehensions use more memory, but are sometimes noticeably faster. Compare the speed of str.join() and tuple() using list comprehensions vs. generator expressions.

Created by Erik Anderson on Fri, 10 Oct 2008 (MIT)
Python recipes (4591)
Erik Anderson's recipes (2)

Required Modules

  • (none specified)

Other Information and Tasks