【发布时间】:2019-03-28 04:13:08
【问题描述】:
我的 python 代码有一些问题。我正在制作一个程序来查找单词中出现的字母A,如果找到该字母并且下一个字母不是字母A,则A 与下一个字母交换。
例如TAN 是TNA 但WHOA 保持WHOA
AARDVARK是ARADVRAK
问题是当我输入ABRACADABRA 时,我得到一个字符串索引超出范围异常。在我遇到那个异常之前,我有一个将它打印为BRACADABRIi 的单词,我不确定为什么必须在我的程序中添加另一个循环。
如果你们还有更有效的方法来运行代码,那么请告诉我!
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换成A会有什么不同吗?
标签: python stringindexoutofbounds