如何利用ast与sys模块实现Python索引切片及特定加密位置消息解密
Hey there! Let's walk through solving this problem from start to finish, covering both the ast/sys module usage and the decryption logic you need.
sys and ast Do Here First, let's clarify why we're using these modules:
sys.stdin.read(): This reads the input provided via standard input (like when you type the encrypted string into the terminal, or pipe it into your script). We add.strip()to clean up any extra newlines or spaces that might come with the input.ast.literal_eval(): This is a safe alternative to the riskyeval()function. It lets us parse input that might be wrapped in quotes (like"ckhoelnknaatia") into a plain string without executing any malicious code. If the input doesn't have quotes, we just use it directly.
Let's recap the encryption rule to reverse-engineer the decryption:
Encryption rule: Take the 1st character of the first word, then the 1st character of the second word; next the 2nd character of the first word, then the 2nd character of the second word; repeat. If words are different lengths, pad the shorter one with
#until they match length before encrypting.
To decrypt, we just reverse this process:
- Split the encrypted string into two separate sequences:
- All characters at even indices (0, 2, 4, ...) belong to the first original word (before padding was added).
- All characters at odd indices (1, 3, 5, ...) belong to the second original word.
- Remove any
#characters from both sequences (these were just padding during encryption). - Convert the results to lowercase (matching the example's output format) and format them as
word1, word2.
Here's the full implementation that follows the code framework you provided:
import ast, sys # Read and clean input, safely parse if quoted input_str = sys.stdin.read().strip() encrypted = ast.literal_eval(input_str) if input_str.startswith(('"', "'")) else input_str # Split encrypted string into two parts using Python slicing message1_chars = encrypted[::2] # Grab every 2nd character starting at index 0 message2_chars = encrypted[1::2] # Grab every 2nd character starting at index 1 # Remove padding and convert to lowercase message1 = message1_chars.replace('#', '').lower() message2 = message2_chars.replace('#', '').lower() # Print the result in the required format print(f"{message1}, {message2}")
If you input ckhoelnknaatia into the script:
encrypted[::2]gives uschennai(characters at positions 0,2,4,6,8,10,12)encrypted[1::2]gives uskolkata(characters at positions 1,3,5,7,9,11,13)- The output will be
chennai, kolkata— exactly matching your example!
内容的提问来源于stack exchange,提问作者Sam2021

