我的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()
答案 0 :(得分:1)
当您到达字符串的末尾并且它是一个'A'时,您的程序将询问字符串末尾的下一个字符。
更改循环,使其不包含最后一个字符:
while count < len(userInput)-1:
if ...
答案 1 :(得分:0)
您可以如下修改代码:
def scrambleWord(userInput):
count = 0
scramble = ''
while count < len(userInput):
if count < len(userInput)-1 and userInput[count] =='A' and userInput[count+1] != 'A':
scramble+= userInput[count+1] + userInput[count]
count+=2
else:
scramble += userInput[count]
count+=1
return scramble
当逻辑试图检查count < len(userInput)-1
的出现并与下一个字母交换时,您没有检查条件(A
)。它将字符串索引超出范围异常。
答案 2 :(得分:0)
当输入的最后一个字符为“ A”时,代码中就会出现问题。 这是因为您的循环中的第一个if试图在最后一次迭代期间访问“ count + 1”个字符。 而且由于该位置没有字符,您会得到索引错误。
最简单的解决方案是为条件设置一个单独的if条件。 while循环的更新代码段可能看起来像这样-
# while start
while count < len_: # len_ is length of input
if count + 1 >= len_:
break # break outta loop, copy last character
current = inp[count]
next_ = inp[count + 1]
if current == 'A':
op += ( next_ + current) # op is result
count += 1
else:
op += current
# increment counter by 1
count += 1
# rest of the code after while is same
代码中的另一个小问题是在复制最后一个字符时(在循环结束之后),您应该使用[]而不是()来引用输入字符串中的最后一个字符。
答案 3 :(得分:0)
只是为了好玩:
from functools import reduce
def main():
word = input("Enter a word: ").lower()
scramble = reduce((lambda x,y : x[:-1]+y+'A' \
if (x[-1]=='a' and y!=x[-1]) \
else x+y),word)
print(scramble.upper())
main()