基于字符位置奇偶性的Python加密解密脚本TypeError问题解决咨询
Hey there! Let's break down what's going wrong here and fix your encryption/decryption script step by step.
The Root Cause of the TypeError
Your error happens because in the loops (for i in message:), i is a character from your input string, not an index number. When you try to run i%2==0, Python interprets the % as a string formatting operator (since i is a string), and it can't match the arguments needed for formatting—hence the "not all arguments converted" error.
Beyond that, there are a few other logic issues in your code that will keep it from working even after fixing the TypeError:
- You're overwriting the encrypted/decrypted string each time instead of appending characters to it.
- You're trying to access
message[num]wherenumis an ASCII value (not an index), which will either throw an index error or give completely wrong results. - Initializing the result with a space will add an unwanted leading space to your output.
Fixed Code with Explanations
Here's the corrected version of your script that implements the position-based encryption/decryption you want:
def encrypt(message): encrypted = "" # Initialize empty string instead of space # Loop through each character with its index (0-based) for idx, char in enumerate(message): # Check if the position is odd/even (adjust if you count positions starting at 1) # If you want position 1 (first character) to be odd, use (idx + 1) % 2 == 1 if idx % 2 == 0: # 0-based index: even indices (0,2,4...) = first, third, fifth characters ascii_num = ord(char) ascii_num += 2 # Shift even-positioned chars up by 2 encrypted += chr(ascii_num) else: ascii_num = ord(char) ascii_num += 1 # Shift odd-positioned chars up by 1 encrypted += chr(ascii_num) return encrypted def decrypt(message): decrypted = "" for idx, char in enumerate(message): if idx % 2 == 0: ascii_num = ord(char) ascii_num -= 2 # Reverse the shift for decryption decrypted += chr(ascii_num) else: ascii_num = ord(char) ascii_num -= 1 decrypted += chr(ascii_num) return decrypted def main(): message = input("Enter the message: ") encrypted_msg = encrypt(message) print("Encrypted message:", encrypted_msg) decrypted_msg = decrypt(encrypted_msg) print("Decrypted message:", decrypted_msg) print("Original message:", message) if __name__ == '__main__': main()
Key Fixes & Notes:
- Using
enumerate(): This gives us both the index (idx) and the character (char) from the input string, so we can check the position correctly. - String Building: Instead of overwriting
encryptedordecryptedeach time, we use+=to append each transformed character to the result string. - ASCII Conversion: We use
ord()to get the character's ASCII value, modify it, thenchr()to convert it back to a character—this is the correct way to shift characters based on their ASCII codes. - Position Counting: The code uses 0-based indexing (first character is index 0, even). If you intended positions to start at 1 (first character is odd position), change the condition to
(idx + 1) % 2 == 1for odd positions, and adjust the decryption logic to match.
Example Output
If you run this with input "Hello World", you'll get:
Enter the message: Hello World Encrypted message: Jfmmp Xpsme Decrypted message: Hello World Original message: Hello World
内容的提问来源于stack exchange,提问作者Devashree Sharma

