Reputation: 9
I want to create a program to encrypt a whole word using Vigenère Cipher . Until now, i can only encrypt one letter a time.
My code so far:
def alpha(shift):
initial_letter = 97 + shift
alpha_list_shift = (list(map(chr, range(initial_letter, 123))))
alpha_list_rest = (list(map(chr, range(97, initial_letter))))
return alpha_list_shift + alpha_list_rest
def encrypt(char_str, char_key):
column_line_alpha = alpha(0)
index_char_key = column_line_alpha.index(char_key)
index_char_str = column_line_alpha.index(char_str)
column_line_alpha_2 = alpha(index_char_key)
return column_line_alpha_2[index_char_str]
Upvotes: 0
Views: 83
Reputation: 564
Short answer: encrypted_string = "".join([encrypt(chr, key) for chr in string_you_want_to_encrypt])
Longer answer: Python has a lot of lovely (to me) ways to elegantly deal with lists, and because strings duck-type to lists, you can use "list comprehension" syntax to dynamically create a new list from your string, then convert it back to a string by using the String type's native "join" method, which will concatenate all the items in an iterable (like a list), gluing them together with the string in question. So, "".join(['x', '2', '#'])
will return the string "x2#"
. The list comprehension lets you call a method on each item as it iterates, so we can call your function for each item, and the result will be in the list returned by the list comprehension, then stitched back into a string by join()
.
Better answer: There might be a good reason encrypt
takes one character at a time, but then every time you call it, you have to handle the loop, and it might make your code a little cleaner/less repetitive if you rewrote encrypt
to take a whole string. Then, you can put the loop inside your method with something like this:
encrypted_string = ""
for letter in input_string:
# [your encryption code]
encrypted_string += newly_encrypted_character
Generally, in Python, you shouldn't need to do something C-like, where you create a loop that uses integers to track your position in a string (or any other iterable, like a tuple or list). "for <item> in <iterable>
" should be able to do the work for you.
Upvotes: 2