输入:
Akash Das
预期回报:
Das Akash
我的代码正在输出:
Da Akash
这是我的代码:
#a
def firstWord(string):
space = string.find(" ")
first = string[:space]
return first
#b
def removeFirst(string):
space = string.find(" ")
word = string[space + 1:]
return word
print(removeFirst("Akash Das"))
#c
def reversePhrase(string):
reverse = []
numSpace = string.count(" ")
reverse.append(firstWord(string))
while numSpace > 0:
string = removeFirst(string)
reverse.insert(0, firstWord(string))
numSpace -= 1
return reverse
def printReverse(string):
for i in reversePhrase(string):
print (i, end = " ")
#d
def main():
string = input("Enter a phrase. ")
print("Your reversed phrase is", end = " ") #call reverse
printReverse(string)
main()
这是输出:
>>>
Das
Enter a phrase. Akash Das
Your reversed phrase is Da Akash
>>>
答案 0 :(得分:2)
CSZ是对的,这更简单。但问题出在firstWord
。如果字符串没有空格,则find
将返回-1。因此space
将为-1,string[:space]
将为string[:-1]
,这是除最后一个之外的所有字符。您只需要检查是否确实找到了空格:
def firstWord(string):
space = string.find(" ")
first = string[:space] if space >= 0 else string
return first
答案 1 :(得分:0)
有更简单的方法:
def main():
string = input("Enter a phrase. ")
print("Your reversed phrase is", end = " ")
print(' '.join(reversed(string.split())))
main()
输出
Enter a phrase. Akash Das
Your reversed phrase is Das Akash
答案 2 :(得分:0)
当find找不到-1时,你没有处理这种情况,当它找不到" "
尝试:
#a
def firstWord(string):
space = string.find(" ")
if space >=0:
first = string[:space]
else:
first = string
return first
答案 3 :(得分:0)
试试这个:
>>> import re
>>> name = 'Harsha Biyani'
>>> s = re.split('\W',s)
>>> s.reverse()
>>> ' '.join(s)
'Biyani Harsha'