在Python中,递增ascii值时出现名称错误

2024-09-28 21:42:38 发布

您现在位置:Python中文网/ 问答频道 /正文

当我尝试将字符串中每个字符的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())  

Tags: 字符串in定义def错误lineglobalabc
2条回答

我想你是想用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'))

有几个错误。这应该管用

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")))))

相关问题 更多 >