【问题标题】:Trouble with for loops in Python 3: getting the index in string2 of an element from string1Python 3 中 for 循环的问题:从 string1 获取元素的 string2 中的索引
【发布时间】:2015-08-18 01:59:08
【问题描述】:

我正在尝试编写一个程序,该程序将获取一个文件并使用 Viginère 密码对其进行编码。我遇到了一些索引问题。我已经像这样定义了我的字符串textalphabet

import string

alphabet = string.ascii_lowercase
ciphertext = open("black_hole.txt","r")
ciphertext = ciphertext.read()
text = ""

for i in range(len(ciphertext)):
    if ciphertext[i].isalpha() == True:
        text = text + ciphertext[i]

当我尝试编写这个 for 循环时,我的麻烦就开始了:

for i in range(len(text)):
    print(alphabet.index(text[i]))

我收到 ValueError“未找到子字符串”。我觉得这很奇怪,因为 text[i] 总是一个字母和一个字符串。

如果我没有足够清楚地提出这个问题,请告诉我!

【问题讨论】:

  • 大写字母呢?
  • 就是这样!非常感谢!

标签: python python-3.x encryption indices vigenere


【解决方案1】:

正如 Kevin 在 cmets 中所说,您可能缺少大写字母。

您可以使用alphabet[ord(text[i].lower()) - ord('a')] 代替index

【讨论】:

    【解决方案2】:
    for i in range(len(text)):
        print(alphabet.index(text.lower()[i]))
    

    只需添加 lower() 就可以了

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-25
      • 2021-05-23
      • 1970-01-01
      • 1970-01-01
      • 2012-01-20
      相关资源
      最近更新 更多