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

在python[关闭]中递增ascii值时出现名称错误

  •  -1
  • BenSmith  · 技术社区  · 6 年前

    当我试图将一个字符串中每个字符的ASCII值增加1时,会引发以下错误:

    错误:

        line 14, in LetterChanges
        incrementLetter("abc")
        line 11, in incrementLetter
        str2 = str2 + chr(ord(str[i]) + 1) 
        NameError: global name 'str2' it is not defined
    

    我相信“str2”在开头是正确定义的,我使用global语句将其放在函数的范围内。为什么python认为没有定义“str2”?

    代码:

    def LetterChanges(str): 
    
        str2=""
    
        def incrementLetter(str):
            global str2
            for i in str:
                str2 = str2 + chr(ord(i) + 1) 
                print(str2)
    
        incrementLetter("abc")
    # keep this function call here  
    print LetterChanges(raw_input())  
    
    2 回复  |  直到 6 年前
        1
  •  2
  •   Jordan Singer    6 年前

    我想你是想利用 enumerate . 你写的方式, i 是字符串而不是整数。

    def incrementLetter(input_string):
      str2 = ""
      for i, character in enumerate(input_string):
        str2 += chr(ord(input_string[i]) + 1)
    
      return str2
    
    print(incrementLetter('test'))
    

    不过,我会使用列表理解来简化您的解决方案:

    def incrementLetter(input_string):
      str2 = ''.join([chr(ord(i) + 1) for i in input_string])
      return str2
    
    print(incrementLetter('test'))
    
        2
  •  0
  •   mad_    6 年前

    有几个错误。这应该管用

    str2=""
    
    def incrementLetter(str1):
        global str2
        for i in str1:
            str2 = str2 + chr(ord(i) + 1) 
            print(str2)
    
    incrementLetter("abc")
    

    一班轮

    print(''.join(map(chr,(i+1 for i in map(ord,"abc")))))
    
    推荐文章