user1768615
user1768615

Reputation: 281

How to rotate chars in string to encrypt message

I'm trying to have fun with one of my buddies, we are special agents but how can we be special agents without having top secret message code to communicate with each other?

# txt = the secret message to convert!
# n = number of times to jump from original position of letter in ASCII code

def spy_code(txt,n):
    result = ''
    for i in txt:
        c = ord(i)+n
        if ord(i) != c:
            b = chr(c)
            result += b
    print result

spy_code('abord mission, dont atk teacher!',5)

After converting message in secret message we are getting one line text...

fgtwi%rnxxnts1%itsy%fyp%yjfhmjw&

problem is, that we'd like to achieve such result:

fgtwi rnxxnts, itsy fyp yjfhmjw!

Considering only letters.

Only use spy code to convert letters and dont convert spaces or special symboles.

Upvotes: 3

Views: 7983

Answers (2)

Necronomicron
Necronomicron

Reputation: 1310

I know this is old, but you can use str.isalpha():

s = 'Impending doom approaches!'
n = 6
result = ''

for c in s:
    result += chr(ord(c) + n) if c.isalpha() else c

print(result)
>>> Osvktjotm juus gvvxuginky!

Upvotes: 1

jlengrand
jlengrand

Reputation: 12827

A simple way to go, using the tip GP89 gave you.

Simply check if your current character is in the list of letter; otherwise just return it as it is

import string

vals = string.letters
def spy_code(txt,n):
    result = ''
    for i in txt:
        if i in vals:
            c = ord(i)+n
            if ord(i) != c:
                b = chr(c)
                result += b
        else:
            result += i
    print result

spy_code('abord mission, dont atk teacher!',5)

returns

fgtwi rnxxnts, itsy fyp yjfhmjw!

Upvotes: 2

Related Questions