[英]How to properly use string indices to create a rot13 equivalent of a string
For my programming class, we have to create a function that takes in a string argument and returns the rot13 equivalent of the string. 对于我的编程类,我们必须创建一个函数,该函数接受一个字符串参数并返回等效于该字符串的rot13。 When I try running my function, it says that count can't equal str[i] because string indices have to be integers. 当我尝试运行函数时,它说count不能等于str [i],因为字符串索引必须是整数。 I'm honestly lost and what else I could do to make the function work. 老实说,我迷路了,我还能做些什么来使该功能正常工作。 Any help would be lovely 任何帮助都会很可爱
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)
In Python, for i in str
will loop through every character in the string str
, with i
set to that character (which you already know, since you're doing ord(i)
). 在Python中, for i in str
将遍历字符串str
中的每个字符,而i
将其设置为该字符(您已经知道了,因为您正在执行ord(i)
)。 (Don't use str
as a name, by the way: str
is the Python name for the string type .) count = str[i]
is treating the character in i
as an index. (顺便说一下,不要使用str
作为名称: str
是字符串类型的Python名称。) count = str[i]
将i
的字符视为索引。 You don't need to (or should) do that. 您不需要(或应该)这样做。 It doesn't make much sense. 这没有多大意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.