代码之家  ›  专栏  ›  技术社区  ›  k_07

Python——我收到一个错误,上面写着“未找到子字符串”

  •  0
  • k_07  · 技术社区  · 3 年前

    我正在尝试为一个类项目制作一个转置密码加密函数。

    from string import ascii_lowercase
    
    def swap(s: str, index0: int, index1: int):
        smaller = index0 if index0 < index1 else index1
        bigger = index0 if index0 >= index1 else index1
        if bigger >= len(s) or smaller < 0:
            return None
        ret = s[:smaller] + s[bigger] + s[smaller+1:]  # swap first
        ret = ret[:bigger] + s[smaller] + s[bigger+1:] # swap second
        return ret
    
    
    def swap_encrypt(s: str, key:str):
        ret = s
        for key_chr in key:
            index = ascii_lowercase.index(key_chr)
            swap_this = index % len(ret)
            with_this = (swap_this + 1) % len(ret)
            ret = swap(ret, swap_this, with_this)
    
        return ret
    s = ''
    key = ''
    def main2():
        s = input('Enter your message: ')
        s = cleanup(s)
        key = input('Enter your keyword: ')
        key = cleanup(key)
        ret= swap_encrypt((s), (key))
        print(cleanup(ret))
    
    main2()
    

    我收到错误“未找到子字符串”,我是否做错了什么?

    如果我的输入是s的=(SLOTH POWER),键的输入是(TOP),那么我的输出应该是:RLOTPOHWES

    是否还有其他方法将函数限制为ord()、len()和range()?如果是这样的话,我也能被展示一下吗?

    错误:

    Traceback (most recent call last):
      File "c:\Users\darks\OneDrive\Documents\7\ciphers.py", line 139, in <module>
        main2()
      File "c:\Users\darks\OneDrive\Documents\7\ciphers.py", line 136, in main2
        ret= swap_encrypt((s), (key))
      File "c:\Users\darks\OneDrive\Documents\7\ciphers.py", line 123, in swap_encrypt
        index = ascii_lowercase.index(key_chr)
    ValueError: substring not found
    
    1 回复  |  直到 3 年前
        1
  •  3
  •   Juraj    3 年前

    它在地图上找不到这个角色 ascii_lowercase ,因为您的输入是大写的。尝试“树懒力量”而不是“树懒力量”,或者使用 s.lower() .