当我尝试将字符串中每个字符的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())
我想你是想用
enumerate
。按照您编写的方式,i
是一个字符串而不是整数。你知道吗不过,我会使用列表理解来简化您的解决方案:
有几个错误。这应该管用
或者
一个班轮
相关问题 更多 >
编程相关推荐