目前,我正在学习《程序员学徒》一书中的Python,我偶然发现了一个练习,我觉得我几乎解决了这个问题,但是当我执行程序时,我遇到了一个错误
以下是练习:
Write a program that takes a string and produces a new string that contains the exact characters that the first string contains, but in order of their ASCII-codes. For instance, the string "Hello, world!" should be turned into " !,Hdellloorw". This is relatively easy to do with list functions, which will be introduced in a future chapter, but for now try to do it with string manipulation functions alone.
我已经添加了下面的代码和错误消息作为图片
from pcinput import getString
entString=getString("Enter your string here: ")
yourString=entString.strip()
def positioner(oldPosition):
newPosition=0
x=0
while x<len(yourString):
if ord(yourString[oldPosition])>ord(yourString[x]):
newPosition+=1
x+=1
return newPosition
i=0
y=0
newString=""
while y<len(yourString):
if positioner(i)==y:
newString+=yourString[i]
y+=1
elif positioner(i)<y:
newString+=yourString[i]
if i<len(yourString):
i+=1
else:
i=0
print(newString)
我做错了什么?我是编程新手
您得到了一个索引错误,因为调用行
if positioner(i)==y:
的值i
等于yourString
的长度yourString[oldPosition]
正在访问一个不存在的索引发生这种情况是因为循环条件(
y<len(yourString)
)没有对i
的值进行任何检查,而这正是导致问题的原因其他一些快速评论:
yourString = input("Enter your string here: ")
替换前四行,因为我不确定pcinput
是什么,并且找不到任何同名的包李>while/x+=1
构造,您可以使用for x in range(len(yourString))
,这更整洁一些李>相关问题 更多 >
编程相关推荐