python - 如何在 Python 中修复字符串索引超出范围异常
问题描述
我的 python 代码有一些问题。我正在制作一个程序来查找单词中出现的字母A
,如果找到该字母并且下一个字母不是该字母A
,则将A
其与下一个字母交换。
作为一个例子,TAN
但TNA
保持WHOA
原样WHOA
AARDVARK
ARADVRAK
问题是当我输入时,ABRACADABRA
我得到一个字符串索引超出范围异常。在我遇到那个异常之前,我有一个打印它的词,因为 BRACADABR
我不确定为什么我必须在我的程序中添加另一个循环。
如果你们还有更有效的方式来运行代码,那么我的方式请告诉我!
def scrambleWord(userInput):
count = 0
scramble = ''
while count < len(userInput):
if userInput[count] =='A' and userInput[count+1] != 'A':
scramble+= userInput[count+1] + userInput[count]
count+=2
elif userInput[count] != 'A':
scramble += userInput[count]
count+=1
if count < len(userInput):
scramble += userInput(len(userInput)-1)
return scramble
#if a is found switch the next letter index with a's index
def main():
userInput = input("Enter a word: ")
finish = scrambleWord(userInput.upper())
print(finish)
main()
解决方案
当您到达字符串的末尾并且它是一个“A”时,您的程序就会询问字符串末尾之外的下一个字符。
更改循环,使其不包含最后一个字符:
while count < len(userInput)-1:
if ...
推荐阅读
- javascript - 如何使用 OnClientClick 事件禁用按钮并启用 OnClick 事件并运行服务器端代码?
- c# - Nancy and razor,“找不到类型名称或命名空间..”
- unity3d - 实例化游戏对象并将其放置在错误位置的场景中
- ruby - 在 Chef 中订阅/通知
- javascript - 多文件输入删除 NET.Core 中的特定文件 Gmail 样式
- ramda.js - 通过管道传递多个参数和最后一个函数的结果
- python - 如何从 Python 中的目录中获取文件?
- python - 使用 matplotlib 在 Python 中绘制热图
- node.js - 如何从通过 AWS API 以字符串格式传入的多部分/表单数据中提取 FROM、TO、SUBJECT、BODY、ATTACHMENT 字段(包含 \n\r)
- java - Eclipse e4 应用程序 - 包含在插件中时找不到 ContextFactory