簡體   English   中英

“未找到子字符串”我做錯了什么?

[英]"substring not found" what am i doing wrong?

我想加密這個密碼,我試圖把它放在一個循環中來處理所有的字母,但它不斷出現錯誤“找不到子字符串”請幫助我不知道我做錯了什么

   n_pword = "hello"
    split_n_pword = []
    n=0
    
    for letter in n_pword:
        split_n_pword.append(letter)
    
    print(split_n_pword)
    
    encrypt = 'abcdefghijklmnopqrstuvwxyz'
    for letter in n_pword:
        index = array.index(split_n_pword[n])
        ceaser = 2
        encrypted_letter = encrypt[index-ceaser]
        n=n+1
    print(encrypted_letter)

如果您正在實施 Casear 密碼,您的代碼似乎有幾個問題。 首先,這是加密和解密數據的代碼版本。

# Make program more robust so it can encrypt uppercase letters also
n_pword = input("Enter text to encrypt it using caser cipher: ").lower()

# It's also better to include numbers so you can include numbers in your plaintext
alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789'
ciphertext = ""
casear_shift_value = 1

for letter in n_pword:
    index = alphabet.index(letter)

# we use mod 36 (26 alphabet + 10 digits 'from 0 to 9')
    ciphertext += alphabet[(index + casear_shift_value) % 36]
print("Encrypted Text {}".format(ciphertext))

# decrypt back
plaintext_back = ""
for letter in ciphertext:
    index = alphabet.index(letter)
    # Reverse operation
    plaintext_back += alphabet[(index - casear_shift_value) % 36]
print("Decrypted plaintext {}".format(plaintext_back))

問題:首先在凱撒密碼中,移位值不會改變。其次,您嘗試使用未聲明的變量array ,這會引發錯誤。 此外,無需將用戶輸入的字符串轉換為數組,python 字符串可以迭代,但您可以考慮將此輸入轉換為小寫,以便程序可以在幾乎所有情況下運行(如果用戶輸入一些特殊字符,則會失敗)。

不確定這是否是您嘗試在單詞中找到字母索引減少 2 從加密中獲取該位置中的字母,並將其添加到 encrypted_letter

n_pword = "hello"
split_n_pword = []
for letter in n_pword: # you can use split_n_pword = list(n_pword)
    split_n_pword.append(letter)
n = 0
encrypt = 'abcdefghijklmnopqrstuvwxyz'
encrypted_letter = "" # you need to create the string before appending to it
for letter in n_pword:
    my_index = n_pword.index(split_n_pword[n]) #index is a string method 
    ceaser = 2
    encrypted_letter += encrypt[my_index-ceaser]
    n+=1

你可以得到相同的結果

n_pword = "hello"
encrypt = 'abcdefghijklmnopqrstuvwxyz'
encrypted_letter = ""
ceaser = 2
for letter in n_pword:
    my_index = n_pword.index(letter )
    encrypted_letter += encrypt[my_index-ceaser]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM