I am working on a small script to encrypt a string that the user provides. The user can also choose how much each character in the string should increment by (on a scale from 1 to 25).
But, I want certain characters to not increment at all (commas, periods, question marks, and spaces) and I have these in a list. How exactly is the possible?
Below is the Python Script.
user_str = str(input("Enter String: "))
user_inc = int(input("How much do you want to increase by: "))
if user_inc > 25:
print("You cannot increase by a number larger than 25.")
elif user_inc <= 0:
print("You cannot increase by a number lower than 1.")
else:
final_str = ""
for letter in user_str:
new_str = ord(letter)
enc_str = new_str + user_inc
if enc_str > 122:
enc_str -= 26
# Here is where I need help.
if letter in [',', '.', ' ', '?']:
letter + enc_str
final_str += chr(enc_str)
print(final_str)
I’ve tried a few different things like trying to add or subtract nothing from the letter, trying to add letter to the final_str, and so far nothing has worked. How exactly can this be done?
>Solution :
You use an if statement to determine whether to add the original value, or the new value to the ciphertext.
[...]
else:
final_str = ""
for letter in user_str:
new_str = ord(letter)
enc_str = new_str + user_inc
if enc_str > 122:
enc_str -= 26
# Here is one idea
if letter in [',', '.', ' ', '?']:
final_str += letter
else:
final_str += chr(enc_str)
print(final_str)