-1

This is a simple encryption code that I've come up with. It uses a single character key.

ar = input('please input string to be de/encrypted:')
key = input('please input single character key:')

def encrypt1(key,ar):
    i = 0
    while i < len(ar):
        br = chr(ord(ar[i])^ord(key))
        i = i+1
        print(br)

encrypt1(key,ar)

print('Input string = ' + ar+'\n'+'key = '+key)

If I input "CMPUT" for the string to be encrypted and 'a' as the key I will get this printed output:

"
,
1
4
5

Which is the correct encryption (according to my assignment example). Now I just have to get those outputs into a single string and print them in the shell like such:

>>>decrypted string: ",145

I've looked through google and old questions on this website but I've still come up empty. I would appreciate your help.

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
magnolia84
  • 11
  • 1
  • possible duplicate of [How can I suppress the newline after a print statement?](http://stackoverflow.com/questions/12102749/how-can-i-suppress-the-newline-after-a-print-statement) – Jasper Mar 18 '15 at 16:27

2 Answers2

0

Most obvious way for a beginner would be to simply accumulate to a string

def encrypt1(key,ar):
    i = 0
    result = ""
    while i < len(ar):
        br = chr(ord(ar[i])^ord(key))
        i = i+1
        result += br
    return result

Usually you would just write it using a generator expression

def encrypt1(key,ar):
    return ''.join(chr(ord(i) ^ ord(key)) for i in ar)
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
0

Check out this code, I believe this is what you need (I changed print(br) line):

ar = input('please input string to be de/encrypted:')
key = input('please input single character key:')

def encrypt1(key,ar):
    i = 0
    while i < len(ar):
        br = chr(ord(ar[i])^ord(key))
        i = i+1
        print(br, end='')

encrypt1(key,ar)

print('\nInput string = ' + ar+'\n'+'key = '+key)
bivo
  • 100
  • 1
  • 2
  • 15
  • I change last line in my example, that should fix the problem. (Simply add `\n`) – bivo Mar 18 '15 at 16:51
  • I literally just figured that out before you posted it (thank god for google). Thanks for your help. This works the best. I would upvote but I'm new to this website. – magnolia84 Mar 18 '15 at 16:52