Create Functions for String Manipulation and Caesar Ciphers in Python
90 likes | 245 Vues
This task involves writing two functions in Python: one that takes a string and returns a spaced-out version, and another that implements a Caesar cipher for text encryption and decryption. The spaced-out function should build a new string by adding spaces between each character. The Caesar cipher function will shift letters based on a set rotation while handling different cases and punctuation. Extend your functions to cope with varying rotations and improve error handling for punctuation in plain text.
Create Functions for String Manipulation and Caesar Ciphers in Python
E N D
Presentation Transcript
Five-minute starter task • Write a function that takes a string argument and returns a spaced out version of the string • E.g. spaceOut("Hello") H e l l o
The spaceOut task • You can iterate over a string, like you can a list: • for x in myString: • do something • You cannot change the letters of a string one by one like this: • for x in myString • x = x + ' ' • You have to build up a NEW STRING and then RETURN IT • newStr = "" • for x in myString • newStr = ….
Examples of string functions in Python Find full documentation here: http://docs.python.org/3/library/string.html
Examples • Plain text:The quick brown fox jumps over the lazy dog • Cipher text:uifrvjdlcspxogpykvnqtpwfsuifmbazeph
Clues: You may find these lines of code useful (they are not in order!) • for x in plainText: • # do something with each letter • y = string.ascii_lowercase.find(x) + 1 • cipherText = cipherText + string.ascii_lowercase[y] • plainText = plainText.lower() • You may also find the % operator useful…
More clues for every character in plain text: index = number of the character in the alphabet index = index + 1 cipher character = index'th letter of alphabet add cipher character to cipher text This will work in most cases, but you will have a problem when you come across a 'z' and when you come across an upper case letter, and when you come across a space or some punctuation character.
Extension tasks • My example only returns cipher text in lower case. Can you write a function that returns mixed cases? • My example will raise an error if the plain text contains punctuation. Can you make your function cope with it? • Write a function that will encrypt txt using ANY rotation. • Write a function that will decrypt anything encrypted using a Caesar cipher.