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

Takes a string and encodes it using a simple cipher.

Python, 49 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
"""
A program for coding and decoding messages
"""
SHIFT = 1

def shift_coder(str):
	"""
	Takes a string and codes it
	"""
	characters = list(str)
	coded_characters = []
	
	for dummy_char in characters:
		ascii_int = ord(dummy_char)
		if ascii_int in range(32) + range(32, 65) + range(91, 97) + \
		range(123, 128):
			new_char = chr(ascii_int)
		elif ascii_int in range(65, 91):
			new_char = chr(((ord(dummy_char) + SHIFT - 65) % 26) + 65)
		elif ascii_int in range(97, 123):
			new_char = chr(((ord(dummy_char) + SHIFT - 97) % 26) + 97)
			
		coded_characters.append(new_char)
		
	coded_str = "".join(coded_characters)
	return coded_str

def shift_decoder(str):
	"""
	Takes a coded string and decodes it into the original message
	"""
	characters = list(str)
	coded_characters = []
	
	for dummy_char in characters:
		ascii_int = ord(dummy_char)
		
		if ascii_int in range(32) + range(32, 65) + range(91, 97) + \
		range(123, 128):
			new_char = chr(ascii_int)
		elif ascii_int in range(65, 91):
			new_char = chr(((ord(dummy_char) - SHIFT - 65) % 26) + 65)
		elif ascii_int in range(97, 123):
			new_char = chr(((ord(dummy_char) - SHIFT - 97) % 26) + 97)
			
		coded_characters.append(new_char)
		
	coded_str = "".join(coded_characters)
	return coded_str

Depending on the value of SHIFT variable, characters in a string are switched. E.g. if SHIFT = 1:

a becomes b, b becomes c, ..., z becomes a

Utilizes ASCII integer values to do the actual coding. Punctuation stays the same, as do lower/upper cases. Also contains a decoder. Give the code to a friend and keep all your messages a secret! (or something like that...)

1 comment

Stephen Driffill (author) 7 years, 4 months ago  # | flag

This program could actually be shortened into just one function if a second argument is given, indicating whether to "code" or "decode". The only difference between the functions is whether to add or subtract the SHIFT value (+ == "code", - == "decode").

Created by Stephen Driffill on Tue, 22 Jul 2014 (MIT)
Python recipes (4591)
Stephen Driffill's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks