【问题标题】:How to properly use string indices to create a rot13 equivalent of a string如何正确使用字符串索引来创建字符串的 rot13 等效项
【发布时间】:2018-04-12 04:14:03
【问题描述】:

对于我的编程课,我们必须创建一个函数,该函数接受一个字符串参数并返回该字符串的 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

【问题讨论】:

  • count = str[i]的目的是什么?
  • @gommb 对我来说,我认为它可以使函数遍历我输入的字符串的每个部分。这不是遍历字符串的正确方法吗?
  • for i in str: 将使其遍历 str 中的每个字符。
  • 只需删除 count = str[i] 并将您使用 count 的任何位置替换为 i
  • @gommb 它正在工作,感谢它!

标签: python string indexing indices


【解决方案1】:
 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 作为名称,顺便说一句:strthe string type 的Python 名称。)count = str[i]i 中的字符视为索引。您不需要(或应该)这样做。没有多大意义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-01
    • 1970-01-01
    • 2015-10-10
    • 1970-01-01
    • 1970-01-01
    • 2019-11-24
    相关资源
    最近更新 更多