[英]How to properly use string indices to create a rot13 equivalent of a string
對於我的編程類,我們必須創建一個函數,該函數接受一個字符串參數並返回等效於該字符串的rot13。 當我嘗試運行函數時,它說count不能等於str [i],因為字符串索引必須是整數。 老實說,我迷路了,我還能做些什么來使該功能正常工作。 任何幫助都會很可愛
def str_rot_13(str):
new_list = []
for i in str:
if ord(i) <= 77:
count = str[i]
k = chr(ord(count) + 13)
new_list.append(k)
if ord(i) > 77 and ord(i) <= 90:
count = str[i]
k = ord(count) - 78
new_list.append(chr(65 + k))
return new_list
for i in str:
if ord(i) <= 77:
count = str[i]
k = chr(ord(count) + 13)
在Python中, for i in str
將遍歷字符串str
中的每個字符,而i
將其設置為該字符(您已經知道了,因為您正在執行ord(i)
)。 (順便說一下,不要使用str
作為名稱: str
是字符串類型的Python名稱。) count = str[i]
將i
的字符視為索引。 您不需要(或應該)這樣做。 這沒有多大意義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.